Did a bunch of svn:eol-style property setting


git-svn-id: https://svn.apache.org/repos/asf/incubator/activemq/trunk/activeio@379619 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannel.java b/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannel.java
index 229cd46..7c36f80 100644
--- a/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannel.java
+++ b/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannel.java
@@ -1,262 +1,262 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.aio;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-import java.net.InetAddress;

-import java.net.Socket;

-import java.net.SocketAddress;

-import java.net.SocketException;

-import java.nio.ByteBuffer;

-

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelListener;

-import org.apache.activeio.stream.sync.socket.SocketMetadata;

-

-import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;

-

-import com.ibm.io.async.AsyncSocketChannel;

-import com.ibm.io.async.IAbstractAsyncFuture;

-import com.ibm.io.async.IAsyncFuture;

-import com.ibm.io.async.ICompletionListener;

-

-/**

- * @version $Revision$

- */

-final public class AIOAsyncChannel implements AsyncChannel, ICompletionListener, SocketMetadata {

-

-    protected static final int DEFAULT_BUFFER_SIZE = ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE;

-

-    private final AsyncSocketChannel socketChannel;

-    private final Socket socket;

-

-    private AsyncChannelListener channelListener;

-    private ByteBuffer inputByteBuffer;

-    

-    private final AtomicBoolean running = new AtomicBoolean(false);

-    private CountDownLatch doneCountDownLatch;

-

-    protected AIOAsyncChannel(AsyncSocketChannel socketChannel) throws IOException {

-        this.socketChannel = socketChannel;

-        this.socket = socketChannel.socket();

-        this.socket.setSendBufferSize(DEFAULT_BUFFER_SIZE);

-        this.socket.setReceiveBufferSize(DEFAULT_BUFFER_SIZE);

-        this.socket.setSoTimeout(0);

-    }

-    

-    private ByteBuffer allocateBuffer() {

-        return ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);

-    }   

-

-    public void setAsyncChannelListener(AsyncChannelListener channelListener) {

-        this.channelListener = channelListener;

-    }

-

-    public AsyncChannelListener getAsyncChannelListener() {

-        return channelListener;

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-

-    public void dispose() {

-        if( running.get() && channelListener!=null ) {

-            channelListener.onPacketError(new SocketException("Socket closed."));

-        }

-        try {

-            stop();

-        } catch (IOException e) {

-        }

-        try {

-            socketChannel.close();

-        } catch (IOException e) {

-        }

-    }

-

-    public void start() throws IOException {

-        if( running.compareAndSet(false, true) ) {

-            doneCountDownLatch = new CountDownLatch(1);

-            requestNextRead();

-        }

-    }

-

-    public void stop() throws IOException {

-        if( running.compareAndSet(true, false) ) {

-            try {

-                doneCountDownLatch.await(5,  TimeUnit.SECONDS);

-            } catch (InterruptedException e) {

-                throw new InterruptedIOException();

-            }

-        }

-    }

-

-    public void write(Packet packet) throws IOException {

-        ByteBuffer data = ((ByteBufferPacket)packet).getByteBuffer();

-        while( data.hasRemaining() ) {

-	        IAsyncFuture future = socketChannel.write(data);

-	        try {

-	            future.getByteCount();

-	        } catch (InterruptedException e) {

-	            throw new InterruptedIOException();

-	        }

-        }

-    }

-

-    public void flush() throws IOException {

-    }

-

-    public void futureCompleted(IAbstractAsyncFuture abstractFuture, Object attribute) {

-        IAsyncFuture future = (IAsyncFuture)abstractFuture;

-        try {

-            

-            if( inputByteBuffer.position()>0 ) {

-	            ByteBuffer remaining = inputByteBuffer.slice();            

-	            Packet data = new ByteBufferPacket(((ByteBuffer)inputByteBuffer.flip()).slice());

-	            

-	            channelListener.onPacket(data);	            

-	            // Keep the remaining buffer around to fill with data.

-	            inputByteBuffer = remaining;

-	            requestNextRead();

-	            

-            } else {                

-                channelListener.onPacket(EOSPacket.EOS_PACKET);  

-            }

-            

-        } catch (IOException e) {

-            channelListener.onPacketError(e);

-        }

-    }

-

-    private void requestNextRead() throws InterruptedIOException {

-        

-        // Don't do next read if we have stopped running.

-        if( !running.get() ) {

-            doneCountDownLatch.countDown();

-            return;

-        }

-        

-        try {

-            

-            if( inputByteBuffer==null || !inputByteBuffer.hasRemaining() ) {

-                inputByteBuffer = allocateBuffer();

-            }

-

-            IAsyncFuture future = socketChannel.read(inputByteBuffer);

-            future.addCompletionListener(this, null, false);

-            

-        } catch (InterruptedException e) {

-            throw new InterruptedIOException();

-        }

-

-    }

-

-    public InetAddress getInetAddress() {

-        return socket.getInetAddress();

-    }

-    public boolean getKeepAlive() throws SocketException {

-        return socket.getKeepAlive();

-    }

-    public InetAddress getLocalAddress() {

-        return socket.getLocalAddress();

-    }

-    public int getLocalPort() {

-        return socket.getLocalPort();

-    }

-    public SocketAddress getLocalSocketAddress() {

-        return socket.getLocalSocketAddress();

-    }

-    public boolean getOOBInline() throws SocketException {

-        return socket.getOOBInline();

-    }

-    public int getPort() {

-        return socket.getPort();

-    }

-    public int getReceiveBufferSize() throws SocketException {

-        return socket.getReceiveBufferSize();

-    }

-    public SocketAddress getRemoteSocketAddress() {

-        return socket.getRemoteSocketAddress();

-    }

-    public boolean getReuseAddress() throws SocketException {

-        return socket.getReuseAddress();

-    }

-    public int getSendBufferSize() throws SocketException {

-        return socket.getSendBufferSize();

-    }

-    public int getSoLinger() throws SocketException {

-        return socket.getSoLinger();

-    }

-    public int getSoTimeout() throws SocketException {

-        return socket.getSoTimeout();

-    }

-    public boolean getTcpNoDelay() throws SocketException {

-        return socket.getTcpNoDelay();

-    }

-    public int getTrafficClass() throws SocketException {

-        return socket.getTrafficClass();

-    }

-    public boolean isBound() {

-        return socket.isBound();

-    }

-    public boolean isClosed() {

-        return socket.isClosed();

-    }

-    public boolean isConnected() {

-        return socket.isConnected();

-    }

-    public void setKeepAlive(boolean on) throws SocketException {

-        socket.setKeepAlive(on);

-    }

-    public void setOOBInline(boolean on) throws SocketException {

-        socket.setOOBInline(on);

-    }

-    public void setReceiveBufferSize(int size) throws SocketException {

-        socket.setReceiveBufferSize(size);

-    }

-    public void setReuseAddress(boolean on) throws SocketException {

-        socket.setReuseAddress(on);

-    }

-    public void setSendBufferSize(int size) throws SocketException {

-        socket.setSendBufferSize(size);

-    }

-    public void setSoLinger(boolean on, int linger) throws SocketException {

-        socket.setSoLinger(on, linger);

-    }

-    public void setTcpNoDelay(boolean on) throws SocketException {

-        socket.setTcpNoDelay(on);

-    }

-    public void setTrafficClass(int tc) throws SocketException {

-        socket.setTrafficClass(tc);

-    }

-    public void setSoTimeout(int i) throws SocketException {

-        socket.setSoTimeout(i);

-    }

-    public String toString() {

-        return "AIO Connection: "+getLocalSocketAddress()+" -> "+getRemoteSocketAddress();

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.aio;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.nio.ByteBuffer;
+
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelListener;
+import org.apache.activeio.stream.sync.socket.SocketMetadata;
+
+import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;
+
+import com.ibm.io.async.AsyncSocketChannel;
+import com.ibm.io.async.IAbstractAsyncFuture;
+import com.ibm.io.async.IAsyncFuture;
+import com.ibm.io.async.ICompletionListener;
+
+/**
+ * @version $Revision$
+ */
+final public class AIOAsyncChannel implements AsyncChannel, ICompletionListener, SocketMetadata {
+
+    protected static final int DEFAULT_BUFFER_SIZE = ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE;
+
+    private final AsyncSocketChannel socketChannel;
+    private final Socket socket;
+
+    private AsyncChannelListener channelListener;
+    private ByteBuffer inputByteBuffer;
+    
+    private final AtomicBoolean running = new AtomicBoolean(false);
+    private CountDownLatch doneCountDownLatch;
+
+    protected AIOAsyncChannel(AsyncSocketChannel socketChannel) throws IOException {
+        this.socketChannel = socketChannel;
+        this.socket = socketChannel.socket();
+        this.socket.setSendBufferSize(DEFAULT_BUFFER_SIZE);
+        this.socket.setReceiveBufferSize(DEFAULT_BUFFER_SIZE);
+        this.socket.setSoTimeout(0);
+    }
+    
+    private ByteBuffer allocateBuffer() {
+        return ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);
+    }   
+
+    public void setAsyncChannelListener(AsyncChannelListener channelListener) {
+        this.channelListener = channelListener;
+    }
+
+    public AsyncChannelListener getAsyncChannelListener() {
+        return channelListener;
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+
+    public void dispose() {
+        if( running.get() && channelListener!=null ) {
+            channelListener.onPacketError(new SocketException("Socket closed."));
+        }
+        try {
+            stop();
+        } catch (IOException e) {
+        }
+        try {
+            socketChannel.close();
+        } catch (IOException e) {
+        }
+    }
+
+    public void start() throws IOException {
+        if( running.compareAndSet(false, true) ) {
+            doneCountDownLatch = new CountDownLatch(1);
+            requestNextRead();
+        }
+    }
+
+    public void stop() throws IOException {
+        if( running.compareAndSet(true, false) ) {
+            try {
+                doneCountDownLatch.await(5,  TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                throw new InterruptedIOException();
+            }
+        }
+    }
+
+    public void write(Packet packet) throws IOException {
+        ByteBuffer data = ((ByteBufferPacket)packet).getByteBuffer();
+        while( data.hasRemaining() ) {
+	        IAsyncFuture future = socketChannel.write(data);
+	        try {
+	            future.getByteCount();
+	        } catch (InterruptedException e) {
+	            throw new InterruptedIOException();
+	        }
+        }
+    }
+
+    public void flush() throws IOException {
+    }
+
+    public void futureCompleted(IAbstractAsyncFuture abstractFuture, Object attribute) {
+        IAsyncFuture future = (IAsyncFuture)abstractFuture;
+        try {
+            
+            if( inputByteBuffer.position()>0 ) {
+	            ByteBuffer remaining = inputByteBuffer.slice();            
+	            Packet data = new ByteBufferPacket(((ByteBuffer)inputByteBuffer.flip()).slice());
+	            
+	            channelListener.onPacket(data);	            
+	            // Keep the remaining buffer around to fill with data.
+	            inputByteBuffer = remaining;
+	            requestNextRead();
+	            
+            } else {                
+                channelListener.onPacket(EOSPacket.EOS_PACKET);  
+            }
+            
+        } catch (IOException e) {
+            channelListener.onPacketError(e);
+        }
+    }
+
+    private void requestNextRead() throws InterruptedIOException {
+        
+        // Don't do next read if we have stopped running.
+        if( !running.get() ) {
+            doneCountDownLatch.countDown();
+            return;
+        }
+        
+        try {
+            
+            if( inputByteBuffer==null || !inputByteBuffer.hasRemaining() ) {
+                inputByteBuffer = allocateBuffer();
+            }
+
+            IAsyncFuture future = socketChannel.read(inputByteBuffer);
+            future.addCompletionListener(this, null, false);
+            
+        } catch (InterruptedException e) {
+            throw new InterruptedIOException();
+        }
+
+    }
+
+    public InetAddress getInetAddress() {
+        return socket.getInetAddress();
+    }
+    public boolean getKeepAlive() throws SocketException {
+        return socket.getKeepAlive();
+    }
+    public InetAddress getLocalAddress() {
+        return socket.getLocalAddress();
+    }
+    public int getLocalPort() {
+        return socket.getLocalPort();
+    }
+    public SocketAddress getLocalSocketAddress() {
+        return socket.getLocalSocketAddress();
+    }
+    public boolean getOOBInline() throws SocketException {
+        return socket.getOOBInline();
+    }
+    public int getPort() {
+        return socket.getPort();
+    }
+    public int getReceiveBufferSize() throws SocketException {
+        return socket.getReceiveBufferSize();
+    }
+    public SocketAddress getRemoteSocketAddress() {
+        return socket.getRemoteSocketAddress();
+    }
+    public boolean getReuseAddress() throws SocketException {
+        return socket.getReuseAddress();
+    }
+    public int getSendBufferSize() throws SocketException {
+        return socket.getSendBufferSize();
+    }
+    public int getSoLinger() throws SocketException {
+        return socket.getSoLinger();
+    }
+    public int getSoTimeout() throws SocketException {
+        return socket.getSoTimeout();
+    }
+    public boolean getTcpNoDelay() throws SocketException {
+        return socket.getTcpNoDelay();
+    }
+    public int getTrafficClass() throws SocketException {
+        return socket.getTrafficClass();
+    }
+    public boolean isBound() {
+        return socket.isBound();
+    }
+    public boolean isClosed() {
+        return socket.isClosed();
+    }
+    public boolean isConnected() {
+        return socket.isConnected();
+    }
+    public void setKeepAlive(boolean on) throws SocketException {
+        socket.setKeepAlive(on);
+    }
+    public void setOOBInline(boolean on) throws SocketException {
+        socket.setOOBInline(on);
+    }
+    public void setReceiveBufferSize(int size) throws SocketException {
+        socket.setReceiveBufferSize(size);
+    }
+    public void setReuseAddress(boolean on) throws SocketException {
+        socket.setReuseAddress(on);
+    }
+    public void setSendBufferSize(int size) throws SocketException {
+        socket.setSendBufferSize(size);
+    }
+    public void setSoLinger(boolean on, int linger) throws SocketException {
+        socket.setSoLinger(on, linger);
+    }
+    public void setTcpNoDelay(boolean on) throws SocketException {
+        socket.setTcpNoDelay(on);
+    }
+    public void setTrafficClass(int tc) throws SocketException {
+        socket.setTrafficClass(tc);
+    }
+    public void setSoTimeout(int i) throws SocketException {
+        socket.setSoTimeout(i);
+    }
+    public String toString() {
+        return "AIO Connection: "+getLocalSocketAddress()+" -> "+getRemoteSocketAddress();
+    }
+
  }
\ No newline at end of file
diff --git a/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelFactory.java b/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelFactory.java
index d37e882..c5d3814 100644
--- a/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelFactory.java
+++ b/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelFactory.java
@@ -1,115 +1,115 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.aio;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.InetSocketAddress;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.adapter.SyncToAsyncChannelServer;

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;

-import org.apache.activeio.util.URISupport;

-

-import com.ibm.io.async.AsyncServerSocketChannel;

-import com.ibm.io.async.AsyncSocketChannel;

-

-/**

- * A TcpAsyncChannelFactory creates {@see org.apache.activeio.net.TcpAsyncChannel}

- * and {@see org.apache.activeio.net.TcpAsyncChannelServer} objects.

- * 

- * @version $Revision$

- */

-public class AIOAsyncChannelFactory implements AsyncChannelFactory {

-

-    protected static final int DEFAULT_BACKLOG = 500;

-    private int backlog = DEFAULT_BACKLOG;

-        

-    /**

-     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.

-     * 

-     * @see org.apache.activeio.AsyncChannelFactory#openAsyncChannel(java.net.URI)

-     */

-    public AsyncChannel openAsyncChannel(URI location) throws IOException {

-        AsyncSocketChannel channel = AsyncSocketChannel.open();

-        channel.connect(new InetSocketAddress(location.getHost(), location.getPort()));

-        return createAsyncChannel(channel);

-    }

-

-    /**

-     * @param channel

-     * @return

-     * @throws IOException

-     */

-    protected AsyncChannel createAsyncChannel(AsyncSocketChannel socketChannel) throws IOException {

-        AsyncChannel channel = new AIOAsyncChannel(socketChannel);

-        channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(true), false);

-        return channel;

-    }

-

-    /**

-     * Binds a server socket a the {@param location}'s port. 

-     * 

-     * @see org.apache.activeio.AsyncChannelFactory#bindAsyncChannel(java.net.URI)

-     */

-    public AsyncChannelServer bindAsyncChannel(URI bindURI) throws IOException {

-        

-        String host = bindURI.getHost();

-        InetSocketAddress address;

-        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            

-            address = new InetSocketAddress(bindURI.getPort());

-        } else {

-            address = new InetSocketAddress(bindURI.getHost(), bindURI.getPort());

-        }

-        

-        AsyncServerSocketChannel serverSocketChannel = AsyncServerSocketChannel.open();

-        serverSocketChannel.socket().bind(address,backlog);

-        

-        URI connectURI = bindURI;

-        try {

-//            connectURI = URISupport.changeHost(connectURI, InetAddress.getLocalHost().getHostName());

-            connectURI = URISupport.changePort(connectURI, serverSocketChannel.socket().getLocalPort());

-        } catch (URISyntaxException e) {

-            throw (IOException)new IOException("Could not build connect URI: "+e).initCause(e);

-        }

-        

-        return SyncToAsyncChannelServer.adapt( 

-                new AIOSyncChannelServer(serverSocketChannel, bindURI, connectURI));

-    }

-    

-    /**

-     * @return Returns the backlog.

-     */

-    public int getBacklog() {

-        return backlog;

-    }

-

-    /**

-     * @param backlog

-     *            The backlog to set.

-     */

-    public void setBacklog(int backlog) {

-        this.backlog = backlog;

-    }

-

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.aio;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.adapter.SyncToAsyncChannelServer;
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;
+import org.apache.activeio.util.URISupport;
+
+import com.ibm.io.async.AsyncServerSocketChannel;
+import com.ibm.io.async.AsyncSocketChannel;
+
+/**
+ * A TcpAsyncChannelFactory creates {@see org.apache.activeio.net.TcpAsyncChannel}
+ * and {@see org.apache.activeio.net.TcpAsyncChannelServer} objects.
+ * 
+ * @version $Revision$
+ */
+public class AIOAsyncChannelFactory implements AsyncChannelFactory {
+
+    protected static final int DEFAULT_BACKLOG = 500;
+    private int backlog = DEFAULT_BACKLOG;
+        
+    /**
+     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
+     * 
+     * @see org.apache.activeio.AsyncChannelFactory#openAsyncChannel(java.net.URI)
+     */
+    public AsyncChannel openAsyncChannel(URI location) throws IOException {
+        AsyncSocketChannel channel = AsyncSocketChannel.open();
+        channel.connect(new InetSocketAddress(location.getHost(), location.getPort()));
+        return createAsyncChannel(channel);
+    }
+
+    /**
+     * @param channel
+     * @return
+     * @throws IOException
+     */
+    protected AsyncChannel createAsyncChannel(AsyncSocketChannel socketChannel) throws IOException {
+        AsyncChannel channel = new AIOAsyncChannel(socketChannel);
+        channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(true), false);
+        return channel;
+    }
+
+    /**
+     * Binds a server socket a the {@param location}'s port. 
+     * 
+     * @see org.apache.activeio.AsyncChannelFactory#bindAsyncChannel(java.net.URI)
+     */
+    public AsyncChannelServer bindAsyncChannel(URI bindURI) throws IOException {
+        
+        String host = bindURI.getHost();
+        InetSocketAddress address;
+        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            
+            address = new InetSocketAddress(bindURI.getPort());
+        } else {
+            address = new InetSocketAddress(bindURI.getHost(), bindURI.getPort());
+        }
+        
+        AsyncServerSocketChannel serverSocketChannel = AsyncServerSocketChannel.open();
+        serverSocketChannel.socket().bind(address,backlog);
+        
+        URI connectURI = bindURI;
+        try {
+//            connectURI = URISupport.changeHost(connectURI, InetAddress.getLocalHost().getHostName());
+            connectURI = URISupport.changePort(connectURI, serverSocketChannel.socket().getLocalPort());
+        } catch (URISyntaxException e) {
+            throw (IOException)new IOException("Could not build connect URI: "+e).initCause(e);
+        }
+        
+        return SyncToAsyncChannelServer.adapt( 
+                new AIOSyncChannelServer(serverSocketChannel, bindURI, connectURI));
+    }
+    
+    /**
+     * @return Returns the backlog.
+     */
+    public int getBacklog() {
+        return backlog;
+    }
+
+    /**
+     * @param backlog
+     *            The backlog to set.
+     */
+    public void setBacklog(int backlog) {
+        this.backlog = backlog;
+    }
+
+
+}
diff --git a/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOSyncChannelServer.java b/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOSyncChannelServer.java
index b6bdc25..f519695 100644
--- a/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOSyncChannelServer.java
+++ b/activeio-aio/src/main/java/org/apache/activeio/packet/async/aio/AIOSyncChannelServer.java
@@ -1,107 +1,107 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.aio;

-

-import java.io.IOException;

-import java.net.SocketException;

-import java.net.SocketTimeoutException;

-import java.net.URI;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-import com.ibm.io.async.AsyncServerSocketChannel;

-

-/**

- * @version $Revision$

- */

-public class AIOSyncChannelServer implements SyncChannelServer {

-

-    private final AsyncServerSocketChannel serverSocket;

-    private final URI bindURI;

-    private final URI connectURI;

-    private int curentSoTimeout;

-

-    public AIOSyncChannelServer(AsyncServerSocketChannel serverSocket, URI bindURI, URI connectURI) throws IOException {

-        this.serverSocket=serverSocket;

-        this.bindURI=bindURI;

-        this.connectURI=connectURI;

-        this.curentSoTimeout = serverSocket.socket().getSoTimeout();

-    }

-    

-    public URI getBindURI() {

-        return bindURI;

-    }

-

-    public URI getConnectURI() {

-        return this.connectURI;

-    }

-

-    public void dispose() {

-        try {

-            serverSocket.close();

-        } catch (IOException e) {

-        }

-    }

-

-    synchronized public void start() throws IOException {

-    }

-

-    synchronized public void stop() {

-    }

-

-    public Channel accept(long timeout) throws IOException {

-        try {

-	        

-            if (timeout == SyncChannelServer.WAIT_FOREVER_TIMEOUT)

-	            setSoTimeout(0);

-	        else if (timeout == SyncChannelServer.NO_WAIT_TIMEOUT)

-	            setSoTimeout(1);

-	        else

-	            setSoTimeout((int) timeout);

-	

-            AsyncChannel channel = new AIOAsyncChannel(serverSocket.accept());

-            channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(true), false);

-            return channel;

-	        

-        } catch (SocketTimeoutException ignore) {

-        }

-        return null;	        

-    }

-

-    private void setSoTimeout(int i) throws SocketException {

-        if (curentSoTimeout != i) {

-            serverSocket.socket().setSoTimeout(i);

-            curentSoTimeout = i;

-        }

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-    

-    public String toString() {

-        return "AIO Server: "+getConnectURI();

-    }

-    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.aio;
+
+import java.io.IOException;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+import com.ibm.io.async.AsyncServerSocketChannel;
+
+/**
+ * @version $Revision$
+ */
+public class AIOSyncChannelServer implements SyncChannelServer {
+
+    private final AsyncServerSocketChannel serverSocket;
+    private final URI bindURI;
+    private final URI connectURI;
+    private int curentSoTimeout;
+
+    public AIOSyncChannelServer(AsyncServerSocketChannel serverSocket, URI bindURI, URI connectURI) throws IOException {
+        this.serverSocket=serverSocket;
+        this.bindURI=bindURI;
+        this.connectURI=connectURI;
+        this.curentSoTimeout = serverSocket.socket().getSoTimeout();
+    }
+    
+    public URI getBindURI() {
+        return bindURI;
+    }
+
+    public URI getConnectURI() {
+        return this.connectURI;
+    }
+
+    public void dispose() {
+        try {
+            serverSocket.close();
+        } catch (IOException e) {
+        }
+    }
+
+    synchronized public void start() throws IOException {
+    }
+
+    synchronized public void stop() {
+    }
+
+    public Channel accept(long timeout) throws IOException {
+        try {
+	        
+            if (timeout == SyncChannelServer.WAIT_FOREVER_TIMEOUT)
+	            setSoTimeout(0);
+	        else if (timeout == SyncChannelServer.NO_WAIT_TIMEOUT)
+	            setSoTimeout(1);
+	        else
+	            setSoTimeout((int) timeout);
+	
+            AsyncChannel channel = new AIOAsyncChannel(serverSocket.accept());
+            channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(true), false);
+            return channel;
+	        
+        } catch (SocketTimeoutException ignore) {
+        }
+        return null;	        
+    }
+
+    private void setSoTimeout(int i) throws SocketException {
+        if (curentSoTimeout != i) {
+            serverSocket.socket().setSoTimeout(i);
+            curentSoTimeout = i;
+        }
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+    
+    public String toString() {
+        return "AIO Server: "+getConnectURI();
+    }
+    
 }
\ No newline at end of file
diff --git a/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelTest.java b/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelTest.java
index 8c954d4..1bb5559 100644
--- a/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelTest.java
+++ b/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/AIOAsyncChannelTest.java
@@ -1,47 +1,47 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.aio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.async.aio.AIOAsyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-

-/**

- * @version $Revision$

- */

-public class AIOAsyncChannelTest extends SyncChannelTestSupport {

-

-    static boolean disabled = System.getProperty("disable.aio.tests", "false").equals("true");    

-    AIOAsyncChannelFactory factory =  new AIOAsyncChannelFactory();

-

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openAsyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindAsyncChannel(new URI("tcp://localhost:0"));

-    }

-

-    protected boolean isDisabled() {

-        return disabled;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.aio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.async.aio.AIOAsyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+
+/**
+ * @version $Revision$
+ */
+public class AIOAsyncChannelTest extends SyncChannelTestSupport {
+
+    static boolean disabled = System.getProperty("disable.aio.tests", "false").equals("true");    
+    AIOAsyncChannelFactory factory =  new AIOAsyncChannelFactory();
+
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openAsyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindAsyncChannel(new URI("tcp://localhost:0"));
+    }
+
+    protected boolean isDisabled() {
+        return disabled;
+    }
+}
diff --git a/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/ChannelFactoryTest.java b/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/ChannelFactoryTest.java
index 85c5a4d..bb75dcb 100644
--- a/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/ChannelFactoryTest.java
+++ b/activeio-aio/src/test/java/org/apache/activeio/packet/async/aio/ChannelFactoryTest.java
@@ -1,111 +1,111 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.aio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import junit.framework.TestCase;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelFactory;

-import org.apache.activeio.adapter.AsyncToSyncChannel;

-import org.apache.activeio.adapter.SyncToAsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.async.aio.AIOAsyncChannel;

-import org.apache.activeio.packet.async.aio.AIOSyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.commons.logging.Log;

-import org.apache.commons.logging.LogFactory;

-

-import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- */

-public class ChannelFactoryTest extends TestCase {

-

-    static final Log log = LogFactory.getLog(ChannelFactoryTest.class);

-    static boolean aioDisabled = System.getProperty("disable.aio.tests", "false").equals("true");

-

-    ChannelFactory factory = new ChannelFactory();

-

-    private SyncChannelServer syncChannelServer;

-    private SyncChannel clientSynchChannel;

-    private SyncChannel serverSynchChannel;

-

-    private AsyncChannelServer asyncChannelServer;

-    private AsyncChannel clientAsyncChannel;

-    private AsyncChannel serverAsyncChannel;

-    

-    protected void setUp() throws Exception {

-        log.info("Running: "+getName());

-    }

-

-    public void testAIO() throws IOException, URISyntaxException, InterruptedException {

-

-        if( aioDisabled ) {

-            return;

-        }

-        

-        createSynchObjects("aio://localhost:0");

-        assertNotNull( syncChannelServer.getAdapter(AIOSyncChannelServer.class) );

-        assertNotNull( clientSynchChannel.getAdapter(AIOAsyncChannel.class) );

-        assertNotNull( serverSynchChannel.getAdapter(AIOAsyncChannel.class) );

-        

-        createAsynchObjects("aio://localhost:0");

-        assertNotNull( asyncChannelServer.getAdapter(AIOSyncChannelServer.class) );

-        assertNotNull( clientAsyncChannel.getAdapter(AIOAsyncChannel.class) );

-        assertNotNull( serverAsyncChannel.getAdapter(AIOAsyncChannel.class) );

-        

-    }    

-

-    private void createSynchObjects(String bindURI) throws IOException, URISyntaxException {

-        syncChannelServer = factory.bindSyncChannel(new URI(bindURI));

-        syncChannelServer.start();

-        clientSynchChannel = factory.openSyncChannel(syncChannelServer.getConnectURI());

-        serverSynchChannel = AsyncToSyncChannel.adapt( syncChannelServer.accept(1000*5) );

-        serverSynchChannel.dispose();        

-        clientSynchChannel.dispose();        

-        syncChannelServer.dispose();

-    }

-

-    private void createAsynchObjects(String bindURI) throws IOException, URISyntaxException, InterruptedException {

-        asyncChannelServer = factory.bindAsyncChannel(new URI(bindURI));

-        final CountDownLatch accepted = new CountDownLatch(1);

-        asyncChannelServer.setAcceptListener(new AcceptListener() {

-            public void onAccept(Channel channel) {

-                serverAsyncChannel = SyncToAsyncChannel.adapt(channel);

-                channel.dispose();

-                accepted.countDown();

-            }

-            public void onAcceptError(IOException error) {

-                error.printStackTrace();

-            }

-        });

-        asyncChannelServer.start();

-        clientAsyncChannel = factory.openAsyncChannel(asyncChannelServer.getConnectURI());

-        accepted.await(1000*10, TimeUnit.MILLISECONDS);

-        clientAsyncChannel.dispose();        

-        asyncChannelServer.dispose();

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.aio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import junit.framework.TestCase;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelFactory;
+import org.apache.activeio.adapter.AsyncToSyncChannel;
+import org.apache.activeio.adapter.SyncToAsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.async.aio.AIOAsyncChannel;
+import org.apache.activeio.packet.async.aio.AIOSyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ */
+public class ChannelFactoryTest extends TestCase {
+
+    static final Log log = LogFactory.getLog(ChannelFactoryTest.class);
+    static boolean aioDisabled = System.getProperty("disable.aio.tests", "false").equals("true");
+
+    ChannelFactory factory = new ChannelFactory();
+
+    private SyncChannelServer syncChannelServer;
+    private SyncChannel clientSynchChannel;
+    private SyncChannel serverSynchChannel;
+
+    private AsyncChannelServer asyncChannelServer;
+    private AsyncChannel clientAsyncChannel;
+    private AsyncChannel serverAsyncChannel;
+    
+    protected void setUp() throws Exception {
+        log.info("Running: "+getName());
+    }
+
+    public void testAIO() throws IOException, URISyntaxException, InterruptedException {
+
+        if( aioDisabled ) {
+            return;
+        }
+        
+        createSynchObjects("aio://localhost:0");
+        assertNotNull( syncChannelServer.getAdapter(AIOSyncChannelServer.class) );
+        assertNotNull( clientSynchChannel.getAdapter(AIOAsyncChannel.class) );
+        assertNotNull( serverSynchChannel.getAdapter(AIOAsyncChannel.class) );
+        
+        createAsynchObjects("aio://localhost:0");
+        assertNotNull( asyncChannelServer.getAdapter(AIOSyncChannelServer.class) );
+        assertNotNull( clientAsyncChannel.getAdapter(AIOAsyncChannel.class) );
+        assertNotNull( serverAsyncChannel.getAdapter(AIOAsyncChannel.class) );
+        
+    }    
+
+    private void createSynchObjects(String bindURI) throws IOException, URISyntaxException {
+        syncChannelServer = factory.bindSyncChannel(new URI(bindURI));
+        syncChannelServer.start();
+        clientSynchChannel = factory.openSyncChannel(syncChannelServer.getConnectURI());
+        serverSynchChannel = AsyncToSyncChannel.adapt( syncChannelServer.accept(1000*5) );
+        serverSynchChannel.dispose();        
+        clientSynchChannel.dispose();        
+        syncChannelServer.dispose();
+    }
+
+    private void createAsynchObjects(String bindURI) throws IOException, URISyntaxException, InterruptedException {
+        asyncChannelServer = factory.bindAsyncChannel(new URI(bindURI));
+        final CountDownLatch accepted = new CountDownLatch(1);
+        asyncChannelServer.setAcceptListener(new AcceptListener() {
+            public void onAccept(Channel channel) {
+                serverAsyncChannel = SyncToAsyncChannel.adapt(channel);
+                channel.dispose();
+                accepted.countDown();
+            }
+            public void onAcceptError(IOException error) {
+                error.printStackTrace();
+            }
+        });
+        asyncChannelServer.start();
+        clientAsyncChannel = factory.openAsyncChannel(asyncChannelServer.getConnectURI());
+        accepted.await(1000*10, TimeUnit.MILLISECONDS);
+        clientAsyncChannel.dispose();        
+        asyncChannelServer.dispose();
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/AcceptListener.java b/activeio-core/src/main/java/org/apache/activeio/AcceptListener.java
index d1af0e2..993b8f0 100644
--- a/activeio-core/src/main/java/org/apache/activeio/AcceptListener.java
+++ b/activeio-core/src/main/java/org/apache/activeio/AcceptListener.java
@@ -1,44 +1,44 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio;

-

-import java.io.IOException;

-

-

-/**

- * An AcceptListener object is used to receive accepted {@see org.apache.activeio.Channel} connections.

- * 

- * @version $Revision$

- */

-public interface AcceptListener {

-    

-	/**

-	 * A {@see AsyncChannelServer} will call this method to when a new channel connection has been

-	 * accepted. 

-	 *   

-	 * @param channel

-	 */

-	void onAccept(Channel channel);

-

-	/**

-	 * A {@see AsyncChannelServer} will call this method when a async failure occurs when accepting

-	 * a connection. 

-     * 

-     * @param error the exception that describes the failure.

-     */

-    void onAcceptError(IOException error);

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio;
+
+import java.io.IOException;
+
+
+/**
+ * An AcceptListener object is used to receive accepted {@see org.apache.activeio.Channel} connections.
+ * 
+ * @version $Revision$
+ */
+public interface AcceptListener {
+    
+	/**
+	 * A {@see AsyncChannelServer} will call this method to when a new channel connection has been
+	 * accepted. 
+	 *   
+	 * @param channel
+	 */
+	void onAccept(Channel channel);
+
+	/**
+	 * A {@see AsyncChannelServer} will call this method when a async failure occurs when accepting
+	 * a connection. 
+     * 
+     * @param error the exception that describes the failure.
+     */
+    void onAcceptError(IOException error);
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/Adaptable.java b/activeio-core/src/main/java/org/apache/activeio/Adaptable.java
index e14917d..6edf9e3 100644
--- a/activeio-core/src/main/java/org/apache/activeio/Adaptable.java
+++ b/activeio-core/src/main/java/org/apache/activeio/Adaptable.java
@@ -1,35 +1,35 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio;

-

-

-/**

- * Provides an Adaptable interface inspired by eclipse's IAdaptable class.  Highly used in ActiveIO since Channel and Packet

- * implementations may be layered and application code may want request the higher level layers/abstractions to adapt to give access

- * to the lower layer implementation details.

- * 

- * @version $Revision$

- */

-public interface Adaptable {

-    

-    /**

-     *  @Return object that is an instance of requested type and is associated this this object.  May return null if no 

-     *  object of that type is associated.

-     */

-    Object getAdapter(Class target);

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio;
+
+
+/**
+ * Provides an Adaptable interface inspired by eclipse's IAdaptable class.  Highly used in ActiveIO since Channel and Packet
+ * implementations may be layered and application code may want request the higher level layers/abstractions to adapt to give access
+ * to the lower layer implementation details.
+ * 
+ * @version $Revision$
+ */
+public interface Adaptable {
+    
+    /**
+     *  @Return object that is an instance of requested type and is associated this this object.  May return null if no 
+     *  object of that type is associated.
+     */
+    Object getAdapter(Class target);
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/Channel.java b/activeio-core/src/main/java/org/apache/activeio/Channel.java
index a055276..c4095a7 100644
--- a/activeio-core/src/main/java/org/apache/activeio/Channel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/Channel.java
@@ -1,31 +1,31 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio;

-

-

-/**

- * A Channel provides a standard procedure for regulating data transmission between 

- * applications.

- * 

- * The activeio API encourages that layered wire protocols be created by wiring

- * together a chain of Channel objects.   

- * 

- * @version $Revision$

- */

-public interface Channel extends Service, Adaptable {    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio;
+
+
+/**
+ * A Channel provides a standard procedure for regulating data transmission between 
+ * applications.
+ * 
+ * The activeio API encourages that layered wire protocols be created by wiring
+ * together a chain of Channel objects.   
+ * 
+ * @version $Revision$
+ */
+public interface Channel extends Service, Adaptable {    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/ChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/ChannelFactory.java
index eb01f68..3ba13b0 100644
--- a/activeio-core/src/main/java/org/apache/activeio/ChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/ChannelFactory.java
@@ -1,144 +1,144 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.util.HashMap;

-

-import org.apache.activeio.adapter.AsyncToSyncChannelFactory;

-import org.apache.activeio.adapter.SyncToAsyncChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.activeio.util.FactoryFinder;

-

-import edu.emory.mathcs.backport.java.util.concurrent.Executor;

-import edu.emory.mathcs.backport.java.util.concurrent.SynchronousQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;

-import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- * A {@see ChannelFactory}uses the requested URI's scheme to determine the

- * actual {@see org.apache.activeio.SynchChannelFactory}or

- * {@see org.apache.activeio.AsyncChannelFactory}implementation to use to create it's

- * {@see org.apache.activeio.Channel}s and {@see org.apache.activeio.ChannelServer}s.

- * 

- * Each URI scheme that {@see ChannelFactory}object handles will have a

- * properties file located at: "META-INF/services/org/apache/activeio/channel/{scheme}".

- * 

- */

-public class ChannelFactory implements SyncChannelFactory, AsyncChannelFactory {

-

-    private final HashMap syncChannelFactoryMap = new HashMap();

-    private final HashMap asyncChannelFactoryMap = new HashMap();

-

-    

-    static public final Executor DEFAULT_EXECUTOR = new ThreadPoolExecutor(10, Integer.MAX_VALUE, 5, TimeUnit.SECONDS, new SynchronousQueue());

-    static {

-        ((ThreadPoolExecutor) DEFAULT_EXECUTOR).setThreadFactory(new ThreadFactory() {

-            public Thread newThread(Runnable run) {

-                Thread thread = new Thread(run);

-                thread.setDaemon(true);

-                return thread;

-            }

-        });

-    }

-

-    private static FactoryFinder finder = new FactoryFinder("META-INF/services/org/apache/activeio/channel/");

-

-    public SyncChannel openSyncChannel(URI location) throws IOException {

-        SyncChannelFactory factory = getSynchChannelFactory(location.getScheme());

-        return factory.openSyncChannel(location);

-    }

-

-    public SyncChannelServer bindSyncChannel(URI location) throws IOException {

-        SyncChannelFactory factory = getSynchChannelFactory(location.getScheme());

-        return factory.bindSyncChannel(location);

-    }

-

-    public AsyncChannel openAsyncChannel(URI location) throws IOException {

-        AsyncChannelFactory factory = getAsyncChannelFactory(location.getScheme());

-        return factory.openAsyncChannel(location);

-    }

-

-    public AsyncChannelServer bindAsyncChannel(URI location) throws IOException {

-        AsyncChannelFactory factory = getAsyncChannelFactory(location.getScheme());

-        return factory.bindAsyncChannel(location);

-    }

-

-    private SyncChannelFactory getSynchChannelFactory(String protocol) throws IOException {

-        try {

-            SyncChannelFactory rc = (SyncChannelFactory) syncChannelFactoryMap.get(protocol);

-            if (rc == null) {

-                try {

-                    rc = (SyncChannelFactory) finder.newInstance(protocol, "SyncChannelFactory.");

-                } catch (Throwable original) {

-                    // try to recovery by using AsyncChannelFactory and adapt

-                    // it to be sync.

-                    try {

-                        AsyncChannelFactory f = (AsyncChannelFactory) finder.newInstance(protocol,

-                                "AsyncChannelFactory.");

-                        rc = AsyncToSyncChannelFactory.adapt(f);

-                    } catch (Throwable e) {

-                        // Recovery strategy failed.. throw original exception.

-                        throw original;

-                    }

-                }

-                syncChannelFactoryMap.put(protocol, rc);

-            }

-            return rc;

-        } catch (Throwable e) {

-            throw (IOException) new IOException("Could not load a SyncChannelFactory for protcol: " + protocol

-                    + ", reason: " + e).initCause(e);

-        }

-    }

-

-    private AsyncChannelFactory getAsyncChannelFactory(String protocol) throws IOException {

-        try {

-            AsyncChannelFactory rc = (AsyncChannelFactory) asyncChannelFactoryMap.get(protocol);

-            if (rc == null) {

-

-                try {

-                    rc = (AsyncChannelFactory) finder.newInstance(protocol, "AsyncChannelFactory.");

-                } catch (Throwable original) {

-                    // try to recovery by using SynchChannelFactory and adapt it

-                    // to be async.

-                    try {

-                        SyncChannelFactory f = (SyncChannelFactory) finder.newInstance(protocol,

-                                "SyncChannelFactory.");

-                        rc = SyncToAsyncChannelFactory.adapt(f);

-                    } catch (Throwable e) {

-                        // Recovery strategy failed.. throw original exception.

-                        throw original;

-                    }

-                }

-

-                asyncChannelFactoryMap.put(protocol, rc);

-            }

-            return rc;

-        } catch (Throwable e) {

-            throw (IOException) new IOException("Could not load a AsyncChannelFactory for protcol: " + protocol

-                    + ", reason: " + e).initCause(e);

-        }

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.HashMap;
+
+import org.apache.activeio.adapter.AsyncToSyncChannelFactory;
+import org.apache.activeio.adapter.SyncToAsyncChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.activeio.util.FactoryFinder;
+
+import edu.emory.mathcs.backport.java.util.concurrent.Executor;
+import edu.emory.mathcs.backport.java.util.concurrent.SynchronousQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;
+import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ * A {@see ChannelFactory}uses the requested URI's scheme to determine the
+ * actual {@see org.apache.activeio.SynchChannelFactory}or
+ * {@see org.apache.activeio.AsyncChannelFactory}implementation to use to create it's
+ * {@see org.apache.activeio.Channel}s and {@see org.apache.activeio.ChannelServer}s.
+ * 
+ * Each URI scheme that {@see ChannelFactory}object handles will have a
+ * properties file located at: "META-INF/services/org/apache/activeio/channel/{scheme}".
+ * 
+ */
+public class ChannelFactory implements SyncChannelFactory, AsyncChannelFactory {
+
+    private final HashMap syncChannelFactoryMap = new HashMap();
+    private final HashMap asyncChannelFactoryMap = new HashMap();
+
+    
+    static public final Executor DEFAULT_EXECUTOR = new ThreadPoolExecutor(10, Integer.MAX_VALUE, 5, TimeUnit.SECONDS, new SynchronousQueue());
+    static {
+        ((ThreadPoolExecutor) DEFAULT_EXECUTOR).setThreadFactory(new ThreadFactory() {
+            public Thread newThread(Runnable run) {
+                Thread thread = new Thread(run);
+                thread.setDaemon(true);
+                return thread;
+            }
+        });
+    }
+
+    private static FactoryFinder finder = new FactoryFinder("META-INF/services/org/apache/activeio/channel/");
+
+    public SyncChannel openSyncChannel(URI location) throws IOException {
+        SyncChannelFactory factory = getSynchChannelFactory(location.getScheme());
+        return factory.openSyncChannel(location);
+    }
+
+    public SyncChannelServer bindSyncChannel(URI location) throws IOException {
+        SyncChannelFactory factory = getSynchChannelFactory(location.getScheme());
+        return factory.bindSyncChannel(location);
+    }
+
+    public AsyncChannel openAsyncChannel(URI location) throws IOException {
+        AsyncChannelFactory factory = getAsyncChannelFactory(location.getScheme());
+        return factory.openAsyncChannel(location);
+    }
+
+    public AsyncChannelServer bindAsyncChannel(URI location) throws IOException {
+        AsyncChannelFactory factory = getAsyncChannelFactory(location.getScheme());
+        return factory.bindAsyncChannel(location);
+    }
+
+    private SyncChannelFactory getSynchChannelFactory(String protocol) throws IOException {
+        try {
+            SyncChannelFactory rc = (SyncChannelFactory) syncChannelFactoryMap.get(protocol);
+            if (rc == null) {
+                try {
+                    rc = (SyncChannelFactory) finder.newInstance(protocol, "SyncChannelFactory.");
+                } catch (Throwable original) {
+                    // try to recovery by using AsyncChannelFactory and adapt
+                    // it to be sync.
+                    try {
+                        AsyncChannelFactory f = (AsyncChannelFactory) finder.newInstance(protocol,
+                                "AsyncChannelFactory.");
+                        rc = AsyncToSyncChannelFactory.adapt(f);
+                    } catch (Throwable e) {
+                        // Recovery strategy failed.. throw original exception.
+                        throw original;
+                    }
+                }
+                syncChannelFactoryMap.put(protocol, rc);
+            }
+            return rc;
+        } catch (Throwable e) {
+            throw (IOException) new IOException("Could not load a SyncChannelFactory for protcol: " + protocol
+                    + ", reason: " + e).initCause(e);
+        }
+    }
+
+    private AsyncChannelFactory getAsyncChannelFactory(String protocol) throws IOException {
+        try {
+            AsyncChannelFactory rc = (AsyncChannelFactory) asyncChannelFactoryMap.get(protocol);
+            if (rc == null) {
+
+                try {
+                    rc = (AsyncChannelFactory) finder.newInstance(protocol, "AsyncChannelFactory.");
+                } catch (Throwable original) {
+                    // try to recovery by using SynchChannelFactory and adapt it
+                    // to be async.
+                    try {
+                        SyncChannelFactory f = (SyncChannelFactory) finder.newInstance(protocol,
+                                "SyncChannelFactory.");
+                        rc = SyncToAsyncChannelFactory.adapt(f);
+                    } catch (Throwable e) {
+                        // Recovery strategy failed.. throw original exception.
+                        throw original;
+                    }
+                }
+
+                asyncChannelFactoryMap.put(protocol, rc);
+            }
+            return rc;
+        } catch (Throwable e) {
+            throw (IOException) new IOException("Could not load a AsyncChannelFactory for protcol: " + protocol
+                    + ", reason: " + e).initCause(e);
+        }
+    }
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/ChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/ChannelServer.java
index 03da42c..98d6ad4 100644
--- a/activeio-core/src/main/java/org/apache/activeio/ChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/ChannelServer.java
@@ -1,51 +1,51 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio;

-

-import java.net.URI;

-

-/**

- * A ChannelServer is used to accept incoming requests to establish new Channel sessions.

- * 

- * Like a normal {@see org.apache.activeio.Channel}, A ChannelServer comes in two falvors, either:

- * {@see org.apache.activeio.AsyncChannelServer} or 

- * {@see org.apache.activeio.SynchChannelServer}.

- * 

- * @version $Revision$

- */

-public interface ChannelServer extends Service, Adaptable {

-

-    /**

-     * The URI that was used when the channel was bound.  This could be different

-     * than what is used by a client to connect to the ChannelServer.  For example,

-     * the bind URI might be tcp://localhost:0 which means the channel should bind to 

-     * an anonymous port.

-     * 

-     * @return The URI that was used when the channel was bound

-     */

-    public URI getBindURI();

-    

-    /**

-     * Once bound, the channel may be able to construct a URI that is more sutible for when 

-     * a client needs to connect to the server.  For examle the port of the URI may be 

-     * updated to reflect the actual local port that the channel server is listening on.

-     * 

-     * @return a URI that a client can use to connect to the server or null if the channel cannot construct the URI.

-     */

-    public URI getConnectURI();

-    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio;
+
+import java.net.URI;
+
+/**
+ * A ChannelServer is used to accept incoming requests to establish new Channel sessions.
+ * 
+ * Like a normal {@see org.apache.activeio.Channel}, A ChannelServer comes in two falvors, either:
+ * {@see org.apache.activeio.AsyncChannelServer} or 
+ * {@see org.apache.activeio.SynchChannelServer}.
+ * 
+ * @version $Revision$
+ */
+public interface ChannelServer extends Service, Adaptable {
+
+    /**
+     * The URI that was used when the channel was bound.  This could be different
+     * than what is used by a client to connect to the ChannelServer.  For example,
+     * the bind URI might be tcp://localhost:0 which means the channel should bind to 
+     * an anonymous port.
+     * 
+     * @return The URI that was used when the channel was bound
+     */
+    public URI getBindURI();
+    
+    /**
+     * Once bound, the channel may be able to construct a URI that is more sutible for when 
+     * a client needs to connect to the server.  For examle the port of the URI may be 
+     * updated to reflect the actual local port that the channel server is listening on.
+     * 
+     * @return a URI that a client can use to connect to the server or null if the channel cannot construct the URI.
+     */
+    public URI getConnectURI();
+    
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/Service.java b/activeio-core/src/main/java/org/apache/activeio/Service.java
index 05ed0f3..4ddf55d 100644
--- a/activeio-core/src/main/java/org/apache/activeio/Service.java
+++ b/activeio-core/src/main/java/org/apache/activeio/Service.java
@@ -1,56 +1,56 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio;

-

-import java.io.IOException;

-

-/**

- * The Service interface is used control the running state of a channel.

- *  

- * Some channels may use background threads to provide SEDA style processing.  By

- * implenting the Service interface, a protcol can allow a container to

- * control those threads.

- *  

- * @version $Revision$

- */

-public interface Service {

-

-	static final public long NO_WAIT_TIMEOUT=0;

-	static final public long WAIT_FOREVER_TIMEOUT=-1;	

-

-	/**

-	 * Starts the channel.  Once started, the channel is in the running state.  

-	 *  

-	 * @throws IOException

-	 */

-    void start() throws IOException;

-

-    /**

-	 * Stops the channel.  Once stopped, the channel is in the stopped state.

-	 * 

-	 * @throws IOException

-	 */

-    void stop() throws IOException;

-        

-    /**

-     * Disposes the channel.  Once disposed, the channel cannot be used anymore.

-     * 

-     * @throws IOException

-     */

-    void dispose();

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio;
+
+import java.io.IOException;
+
+/**
+ * The Service interface is used control the running state of a channel.
+ *  
+ * Some channels may use background threads to provide SEDA style processing.  By
+ * implenting the Service interface, a protcol can allow a container to
+ * control those threads.
+ *  
+ * @version $Revision$
+ */
+public interface Service {
+
+	static final public long NO_WAIT_TIMEOUT=0;
+	static final public long WAIT_FOREVER_TIMEOUT=-1;	
+
+	/**
+	 * Starts the channel.  Once started, the channel is in the running state.  
+	 *  
+	 * @throws IOException
+	 */
+    void start() throws IOException;
+
+    /**
+	 * Stops the channel.  Once stopped, the channel is in the stopped state.
+	 * 
+	 * @throws IOException
+	 */
+    void stop() throws IOException;
+        
+    /**
+     * Disposes the channel.  Once disposed, the channel cannot be used anymore.
+     * 
+     * @throws IOException
+     */
+    void dispose();
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncChannelToOutputStream.java b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncChannelToOutputStream.java
index a9980f9..6adf962 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncChannelToOutputStream.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncChannelToOutputStream.java
@@ -1,72 +1,72 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.OutputStream;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.BytePacket;

-import org.apache.activeio.packet.async.AsyncChannel;

-

-/**

- */

-public class AsyncChannelToOutputStream extends OutputStream {

-

-    private final AsyncChannel channel;

-    private boolean closed;

-

-    /**

-     * @param channel

-     */

-    public AsyncChannelToOutputStream(AsyncChannel channel) {

-        this.channel = channel;

-    }

-

-    /**

-     * @see java.io.OutputStream#write(int)

-     */

-    public void write(int b) throws IOException {

-        channel.write(new BytePacket((byte) b));

-    }

-

-    /**

-     * @see java.io.OutputStream#write(byte[], int, int)

-     */

-    public void write(byte[] b, int off, int len) throws IOException {

-        channel.write(new ByteArrayPacket(b, off, len));

-    }

-    

-    /**

-     * @see java.io.OutputStream#flush()

-     */

-    public void flush() throws IOException {

-        channel.flush();

-    }

-            

-    /**

-     * @see java.io.InputStream#close()

-     */

-    public void close() throws IOException {

-        closed=true;

-        super.close();

-    }

-    

-    public boolean isClosed() {

-        return closed;

-    }    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.BytePacket;
+import org.apache.activeio.packet.async.AsyncChannel;
+
+/**
+ */
+public class AsyncChannelToOutputStream extends OutputStream {
+
+    private final AsyncChannel channel;
+    private boolean closed;
+
+    /**
+     * @param channel
+     */
+    public AsyncChannelToOutputStream(AsyncChannel channel) {
+        this.channel = channel;
+    }
+
+    /**
+     * @see java.io.OutputStream#write(int)
+     */
+    public void write(int b) throws IOException {
+        channel.write(new BytePacket((byte) b));
+    }
+
+    /**
+     * @see java.io.OutputStream#write(byte[], int, int)
+     */
+    public void write(byte[] b, int off, int len) throws IOException {
+        channel.write(new ByteArrayPacket(b, off, len));
+    }
+    
+    /**
+     * @see java.io.OutputStream#flush()
+     */
+    public void flush() throws IOException {
+        channel.flush();
+    }
+            
+    /**
+     * @see java.io.InputStream#close()
+     */
+    public void close() throws IOException {
+        closed=true;
+        super.close();
+    }
+    
+    public boolean isClosed() {
+        return closed;
+    }    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannel.java
index d158e0c..35b6722 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannel.java
@@ -1,180 +1,180 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelListener;

-import org.apache.activeio.packet.sync.SyncChannel;

-

-import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- * Adapts a {@see org.apache.activeio.AsyncChannel} so that it provides an 

- * {@see org.apache.activeio.SynchChannel} interface.  

- * 

- * This object buffers asynchronous messages from the {@see org.apache.activeio.AsyncChannel} 

- * and buffers them in a {@see edu.emory.mathcs.backport.java.util.concurrent.Channel} util the client receives them.

- * 

- * @version $Revision$

- */

-final public class AsyncToSyncChannel implements SyncChannel, AsyncChannelListener {

-

-    private final AsyncChannel asyncChannel;    

-    private final BlockingQueue buffer;

-

-    static public SyncChannel adapt(org.apache.activeio.Channel channel) {

-        return adapt(channel, new LinkedBlockingQueue());

-    }

-

-    static public SyncChannel adapt(org.apache.activeio.Channel channel, BlockingQueue upPacketChannel) {

-

-        // It might not need adapting

-        if( channel instanceof SyncChannel ) {

-            return (SyncChannel) channel;

-        }

-

-        // Can we just just undo the adaptor

-        if( channel.getClass() == SyncToAsyncChannel.class ) {

-            return ((SyncToAsyncChannel)channel).getSynchChannel();

-        }

-        

-        return new AsyncToSyncChannel((AsyncChannel)channel, upPacketChannel);        

-    }

-    

-    /**

-     * @deprecated {@see #adapt(AsyncChannel)}

-     */

-    public AsyncToSyncChannel(AsyncChannel asyncChannel) {

-        this(asyncChannel, new LinkedBlockingQueue());

-    }

-    

-    /**

-     * @deprecated {@see #adapt(AsyncChannel, Channel)}

-     */

-    public AsyncToSyncChannel(AsyncChannel asyncChannel, BlockingQueue upPacketChannel){

-        this.asyncChannel = asyncChannel;

-        this.asyncChannel.setAsyncChannelListener(this);

-        this.buffer=upPacketChannel;

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)

-     */

-    public void write(org.apache.activeio.packet.Packet packet) throws IOException {

-        asyncChannel.write(packet);

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#flush()

-     */

-    public void flush() throws IOException {

-        asyncChannel.flush();

-    }

-

-    /**

-     * @see org.apache.activeio.packet.sync.SyncChannel#read(long)

-     */

-    public Packet read(long timeout) throws IOException {

-        try {

-            

-            Object o;

-            if( timeout == NO_WAIT_TIMEOUT ) {

-                o = buffer.poll(0, TimeUnit.MILLISECONDS);

-            } else if( timeout == WAIT_FOREVER_TIMEOUT ) {

-                o = buffer.take();            

-            } else {

-                o = buffer.poll(timeout, TimeUnit.MILLISECONDS);                        

-            }

-            

-            if( o == null )

-                return null;

-            

-            if( o instanceof Packet )

-                return (Packet)o;     

-            

-            Throwable e = (Throwable)o;

-            throw (IOException)new IOException("Async error occurred: "+e).initCause(e);

-            

-        } catch (InterruptedException e) {

-            throw new InterruptedIOException(e.getMessage());

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        asyncChannel.dispose();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#start()

-     */

-    public void start() throws IOException {

-        asyncChannel.start();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#stop()

-     */

-    public void stop() throws IOException {

-        asyncChannel.stop();

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacket(org.apache.activeio.packet.Packet)

-     */

-    public void onPacket(Packet packet) {

-        try {

-            buffer.put(packet);

-        } catch (InterruptedException e) {

-            Thread.currentThread().interrupt();

-        }        

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacketError(org.apache.activeio.ChannelException)

-     */

-    public void onPacketError(IOException error) {

-        try {

-            buffer.put(error);

-        } catch (InterruptedException e) {

-            Thread.currentThread().interrupt();

-        }        

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return asyncChannel.getAdapter(target);

-    }    

-

-    public AsyncChannel getAsyncChannel() {

-        return asyncChannel;

-    }

-    

-    public String toString() {

-        return asyncChannel.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelListener;
+import org.apache.activeio.packet.sync.SyncChannel;
+
+import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ * Adapts a {@see org.apache.activeio.AsyncChannel} so that it provides an 
+ * {@see org.apache.activeio.SynchChannel} interface.  
+ * 
+ * This object buffers asynchronous messages from the {@see org.apache.activeio.AsyncChannel} 
+ * and buffers them in a {@see edu.emory.mathcs.backport.java.util.concurrent.Channel} util the client receives them.
+ * 
+ * @version $Revision$
+ */
+final public class AsyncToSyncChannel implements SyncChannel, AsyncChannelListener {
+
+    private final AsyncChannel asyncChannel;    
+    private final BlockingQueue buffer;
+
+    static public SyncChannel adapt(org.apache.activeio.Channel channel) {
+        return adapt(channel, new LinkedBlockingQueue());
+    }
+
+    static public SyncChannel adapt(org.apache.activeio.Channel channel, BlockingQueue upPacketChannel) {
+
+        // It might not need adapting
+        if( channel instanceof SyncChannel ) {
+            return (SyncChannel) channel;
+        }
+
+        // Can we just just undo the adaptor
+        if( channel.getClass() == SyncToAsyncChannel.class ) {
+            return ((SyncToAsyncChannel)channel).getSynchChannel();
+        }
+        
+        return new AsyncToSyncChannel((AsyncChannel)channel, upPacketChannel);        
+    }
+    
+    /**
+     * @deprecated {@see #adapt(AsyncChannel)}
+     */
+    public AsyncToSyncChannel(AsyncChannel asyncChannel) {
+        this(asyncChannel, new LinkedBlockingQueue());
+    }
+    
+    /**
+     * @deprecated {@see #adapt(AsyncChannel, Channel)}
+     */
+    public AsyncToSyncChannel(AsyncChannel asyncChannel, BlockingQueue upPacketChannel){
+        this.asyncChannel = asyncChannel;
+        this.asyncChannel.setAsyncChannelListener(this);
+        this.buffer=upPacketChannel;
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)
+     */
+    public void write(org.apache.activeio.packet.Packet packet) throws IOException {
+        asyncChannel.write(packet);
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#flush()
+     */
+    public void flush() throws IOException {
+        asyncChannel.flush();
+    }
+
+    /**
+     * @see org.apache.activeio.packet.sync.SyncChannel#read(long)
+     */
+    public Packet read(long timeout) throws IOException {
+        try {
+            
+            Object o;
+            if( timeout == NO_WAIT_TIMEOUT ) {
+                o = buffer.poll(0, TimeUnit.MILLISECONDS);
+            } else if( timeout == WAIT_FOREVER_TIMEOUT ) {
+                o = buffer.take();            
+            } else {
+                o = buffer.poll(timeout, TimeUnit.MILLISECONDS);                        
+            }
+            
+            if( o == null )
+                return null;
+            
+            if( o instanceof Packet )
+                return (Packet)o;     
+            
+            Throwable e = (Throwable)o;
+            throw (IOException)new IOException("Async error occurred: "+e).initCause(e);
+            
+        } catch (InterruptedException e) {
+            throw new InterruptedIOException(e.getMessage());
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        asyncChannel.dispose();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#start()
+     */
+    public void start() throws IOException {
+        asyncChannel.start();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#stop()
+     */
+    public void stop() throws IOException {
+        asyncChannel.stop();
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacket(org.apache.activeio.packet.Packet)
+     */
+    public void onPacket(Packet packet) {
+        try {
+            buffer.put(packet);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+        }        
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacketError(org.apache.activeio.ChannelException)
+     */
+    public void onPacketError(IOException error) {
+        try {
+            buffer.put(error);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+        }        
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return asyncChannel.getAdapter(target);
+    }    
+
+    public AsyncChannel getAsyncChannel() {
+        return asyncChannel;
+    }
+    
+    public String toString() {
+        return asyncChannel.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelFactory.java
index 2a678f8..b4d1b11 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelFactory.java
@@ -1,65 +1,65 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.packet.async.AsyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-/**

- * @version $Revision$

- */

-final public class AsyncToSyncChannelFactory implements SyncChannelFactory {

-    

-    private AsyncChannelFactory asyncChannelFactory;

-    

-    static public SyncChannelFactory adapt(AsyncChannelFactory channelFactory ) {

-

-        // It might not need adapting

-        if( channelFactory instanceof SyncChannelServer ) {

-            return (SyncChannelFactory) channelFactory;

-        }

-

-        // Can we just just undo the adaptor

-        if( channelFactory.getClass() == SyncToAsyncChannelFactory.class ) {

-            return ((SyncToAsyncChannelFactory)channelFactory).getSyncChannelFactory();

-        }

-        

-        return new AsyncToSyncChannelFactory((AsyncChannelFactory)channelFactory);        

-    }

-    

-    

-    private AsyncToSyncChannelFactory(AsyncChannelFactory asyncChannelFactory) {

-        this.asyncChannelFactory = asyncChannelFactory;

-    }

-        

-    public SyncChannel openSyncChannel(URI location) throws IOException {

-        return AsyncToSyncChannel.adapt( asyncChannelFactory.openAsyncChannel(location) );

-    }

-    

-    public SyncChannelServer bindSyncChannel(URI location) throws IOException {

-        return AsyncToSyncChannelServer.adapt(asyncChannelFactory.bindAsyncChannel(location));

-    }

-    

-    public AsyncChannelFactory getAsyncChannelFactory() {

-        return asyncChannelFactory;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.packet.async.AsyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+/**
+ * @version $Revision$
+ */
+final public class AsyncToSyncChannelFactory implements SyncChannelFactory {
+    
+    private AsyncChannelFactory asyncChannelFactory;
+    
+    static public SyncChannelFactory adapt(AsyncChannelFactory channelFactory ) {
+
+        // It might not need adapting
+        if( channelFactory instanceof SyncChannelServer ) {
+            return (SyncChannelFactory) channelFactory;
+        }
+
+        // Can we just just undo the adaptor
+        if( channelFactory.getClass() == SyncToAsyncChannelFactory.class ) {
+            return ((SyncToAsyncChannelFactory)channelFactory).getSyncChannelFactory();
+        }
+        
+        return new AsyncToSyncChannelFactory((AsyncChannelFactory)channelFactory);        
+    }
+    
+    
+    private AsyncToSyncChannelFactory(AsyncChannelFactory asyncChannelFactory) {
+        this.asyncChannelFactory = asyncChannelFactory;
+    }
+        
+    public SyncChannel openSyncChannel(URI location) throws IOException {
+        return AsyncToSyncChannel.adapt( asyncChannelFactory.openAsyncChannel(location) );
+    }
+    
+    public SyncChannelServer bindSyncChannel(URI location) throws IOException {
+        return AsyncToSyncChannelServer.adapt(asyncChannelFactory.bindAsyncChannel(location));
+    }
+    
+    public AsyncChannelFactory getAsyncChannelFactory() {
+        return asyncChannelFactory;
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelServer.java
index b16b345..57b7d67 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/AsyncToSyncChannelServer.java
@@ -1,176 +1,176 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-import java.net.URI;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- * Adapts a {@see org.apache.activeio.AsyncChannelServer} so that it provides an 

- * {@see org.apache.activeio.SynchChannelServer} interface.  

- * 

- * This object buffers asynchronous accepts from the {@see org.apache.activeio.AsyncChannelServer} 

- * abs buffers them in a {@see edu.emory.mathcs.backport.java.util.concurrent.Channel} util the client accepts the 

- * connection.

- * 

- * @version $Revision$

- */

-final public class AsyncToSyncChannelServer implements SyncChannelServer, AcceptListener {

-

-    private final AsyncChannelServer asyncChannelServer;    

-    private final BlockingQueue acceptBuffer;

-    

-    static public SyncChannelServer adapt(ChannelServer channel) {

-        return adapt(channel, new LinkedBlockingQueue());

-    }

-

-    static public SyncChannelServer adapt(ChannelServer channel, BlockingQueue upPacketChannel) {

-

-        // It might not need adapting

-        if( channel instanceof SyncChannelServer ) {

-            return (SyncChannelServer) channel;

-        }

-

-        // Can we just just undo the adaptor

-        if( channel.getClass() == SyncToAsyncChannel.class ) {

-            return ((SyncToAsyncChannelServer)channel).getSynchChannelServer();

-        }

-        

-        return new AsyncToSyncChannelServer((AsyncChannelServer)channel, upPacketChannel);        

-    }

-    

-    /**

-     * @deprecated {@see #adapt(ChannelServer)}

-     */

-    public AsyncToSyncChannelServer(AsyncChannelServer asyncChannelServer) {

-        this(asyncChannelServer,new LinkedBlockingQueue());

-    }

-    

-    /**

-     * @deprecated {@see #adapt(ChannelServer, edu.emory.mathcs.backport.java.util.concurrent.Channel)}

-     */

-    public AsyncToSyncChannelServer(AsyncChannelServer asyncChannelServer, BlockingQueue acceptBuffer) {

-        this.asyncChannelServer = asyncChannelServer;

-        this.acceptBuffer=acceptBuffer;

-        this.asyncChannelServer.setAcceptListener(this);

-    }

-

-    /**

-     * @see org.apache.activeio.packet.sync.SyncChannelServer#accept(long)

-     */

-    public org.apache.activeio.Channel accept(long timeout) throws IOException {

-        try {

-            

-            Object o;

-            if( timeout == NO_WAIT_TIMEOUT ) {

-                o = acceptBuffer.poll(0, TimeUnit.MILLISECONDS);

-            } else if( timeout == WAIT_FOREVER_TIMEOUT ) {

-                o = acceptBuffer.take();            

-            } else {

-                o = acceptBuffer.poll(timeout, TimeUnit.MILLISECONDS);                        

-            }

-            

-            if( o == null )

-                return null;

-            

-            if( o instanceof Channel )

-                return (Channel)o;

-            

-            Throwable e = (Throwable)o;

-            throw (IOException)new IOException("Async error occurred: "+e).initCause(e);

-            

-        } catch (InterruptedException e) {

-            throw new InterruptedIOException(e.getMessage());

-        }

-    }

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        asyncChannelServer.dispose();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#start()

-     */

-    public void start() throws IOException {

-        asyncChannelServer.start();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#stop()

-     */

-    public void stop() throws IOException {

-        asyncChannelServer.stop();

-    }

-

-    public URI getBindURI() {

-        return asyncChannelServer.getBindURI();

-    }

-

-    public URI getConnectURI() {

-        return asyncChannelServer.getConnectURI();

-    }

-

-    /**

-     * @see org.apache.activeio.AcceptListener#onAccept(org.apache.activeio.Channel)

-     */

-    public void onAccept(org.apache.activeio.Channel channel) {

-        try {

-            acceptBuffer.put(channel);

-        } catch (InterruptedException e) {

-            Thread.currentThread().interrupt();

-        }        

-    }

-    

-    /**

-     * @see org.apache.activeio.AcceptListener#onAcceptError(java.io.IOException)

-     */

-    public void onAcceptError(IOException error) {

-        try {

-            acceptBuffer.put(error);

-        } catch (InterruptedException e) {

-            Thread.currentThread().interrupt();

-        }        

-    }

-    

-    public AsyncChannelServer getAsyncChannelServer() {

-        return asyncChannelServer;

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return asyncChannelServer.getAdapter(target);

-    }    

-    

-    public String toString() {

-        return asyncChannelServer.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.URI;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ * Adapts a {@see org.apache.activeio.AsyncChannelServer} so that it provides an 
+ * {@see org.apache.activeio.SynchChannelServer} interface.  
+ * 
+ * This object buffers asynchronous accepts from the {@see org.apache.activeio.AsyncChannelServer} 
+ * abs buffers them in a {@see edu.emory.mathcs.backport.java.util.concurrent.Channel} util the client accepts the 
+ * connection.
+ * 
+ * @version $Revision$
+ */
+final public class AsyncToSyncChannelServer implements SyncChannelServer, AcceptListener {
+
+    private final AsyncChannelServer asyncChannelServer;    
+    private final BlockingQueue acceptBuffer;
+    
+    static public SyncChannelServer adapt(ChannelServer channel) {
+        return adapt(channel, new LinkedBlockingQueue());
+    }
+
+    static public SyncChannelServer adapt(ChannelServer channel, BlockingQueue upPacketChannel) {
+
+        // It might not need adapting
+        if( channel instanceof SyncChannelServer ) {
+            return (SyncChannelServer) channel;
+        }
+
+        // Can we just just undo the adaptor
+        if( channel.getClass() == SyncToAsyncChannel.class ) {
+            return ((SyncToAsyncChannelServer)channel).getSynchChannelServer();
+        }
+        
+        return new AsyncToSyncChannelServer((AsyncChannelServer)channel, upPacketChannel);        
+    }
+    
+    /**
+     * @deprecated {@see #adapt(ChannelServer)}
+     */
+    public AsyncToSyncChannelServer(AsyncChannelServer asyncChannelServer) {
+        this(asyncChannelServer,new LinkedBlockingQueue());
+    }
+    
+    /**
+     * @deprecated {@see #adapt(ChannelServer, edu.emory.mathcs.backport.java.util.concurrent.Channel)}
+     */
+    public AsyncToSyncChannelServer(AsyncChannelServer asyncChannelServer, BlockingQueue acceptBuffer) {
+        this.asyncChannelServer = asyncChannelServer;
+        this.acceptBuffer=acceptBuffer;
+        this.asyncChannelServer.setAcceptListener(this);
+    }
+
+    /**
+     * @see org.apache.activeio.packet.sync.SyncChannelServer#accept(long)
+     */
+    public org.apache.activeio.Channel accept(long timeout) throws IOException {
+        try {
+            
+            Object o;
+            if( timeout == NO_WAIT_TIMEOUT ) {
+                o = acceptBuffer.poll(0, TimeUnit.MILLISECONDS);
+            } else if( timeout == WAIT_FOREVER_TIMEOUT ) {
+                o = acceptBuffer.take();            
+            } else {
+                o = acceptBuffer.poll(timeout, TimeUnit.MILLISECONDS);                        
+            }
+            
+            if( o == null )
+                return null;
+            
+            if( o instanceof Channel )
+                return (Channel)o;
+            
+            Throwable e = (Throwable)o;
+            throw (IOException)new IOException("Async error occurred: "+e).initCause(e);
+            
+        } catch (InterruptedException e) {
+            throw new InterruptedIOException(e.getMessage());
+        }
+    }
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        asyncChannelServer.dispose();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#start()
+     */
+    public void start() throws IOException {
+        asyncChannelServer.start();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#stop()
+     */
+    public void stop() throws IOException {
+        asyncChannelServer.stop();
+    }
+
+    public URI getBindURI() {
+        return asyncChannelServer.getBindURI();
+    }
+
+    public URI getConnectURI() {
+        return asyncChannelServer.getConnectURI();
+    }
+
+    /**
+     * @see org.apache.activeio.AcceptListener#onAccept(org.apache.activeio.Channel)
+     */
+    public void onAccept(org.apache.activeio.Channel channel) {
+        try {
+            acceptBuffer.put(channel);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+        }        
+    }
+    
+    /**
+     * @see org.apache.activeio.AcceptListener#onAcceptError(java.io.IOException)
+     */
+    public void onAcceptError(IOException error) {
+        try {
+            acceptBuffer.put(error);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+        }        
+    }
+    
+    public AsyncChannelServer getAsyncChannelServer() {
+        return asyncChannelServer;
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return asyncChannelServer.getAdapter(target);
+    }    
+    
+    public String toString() {
+        return asyncChannelServer.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/PacketByteArrayOutputStream.java b/activeio-core/src/main/java/org/apache/activeio/adapter/PacketByteArrayOutputStream.java
index e64d4c3..407872a 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/PacketByteArrayOutputStream.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/PacketByteArrayOutputStream.java
@@ -1,109 +1,109 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.OutputStream;

-

-import org.apache.activeio.packet.AppendedPacket;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-

-/**

- *

- */

-final public class PacketByteArrayOutputStream extends OutputStream {

-    

-    private Packet result;

-    private Packet current;

-    int nextAllocationSize=0;

-    

-    public PacketByteArrayOutputStream() {

-    	this( 1024 );

-    }

-    

-    public PacketByteArrayOutputStream(int initialSize) {

-    	nextAllocationSize = initialSize;

-        current = allocate();

-    }

-    

-    protected Packet allocate() {

-    	ByteArrayPacket packet = new ByteArrayPacket(new byte[nextAllocationSize]);

-    	nextAllocationSize <<= 3; // x by 8

-        return packet;

-    }

-    

-    public void skip(int size) {

-        while( size > 0 ) {

-            if( !current.hasRemaining() ) {

-                allocatedNext();

-            }

-            

-            int skip = ((size <= current.remaining()) ? size : current.remaining());

-            current.position(current.position()+skip);

-            size -= skip;

-        }

-    }

-    

-    public void write(int b) throws IOException {

-        if( !current.hasRemaining() ) {

-            allocatedNext();

-        }

-        current.write(b);

-    }

-    

-    public void write(byte[] b, int off, int len) throws IOException {

-        while( len > 0 ) {

-	        if( !current.hasRemaining() ) {

-	            allocatedNext();

-	        }

-	        int wrote = current.write(b,off,len);

-	        off+=wrote;

-	        len-=wrote;

-        }

-    }

-    

-    private void allocatedNext() {

-        if( result == null ) {

-            current.flip();

-            result = current;

-        } else {

-            current.flip();

-            result = AppendedPacket.join(result, current);            

-        }

-        current = allocate();

-    }

-    

-    public Packet getPacket() {

-        if( result == null ) {

-            current.flip();

-            return current.slice();

-        } else {

-            current.flip();

-            return AppendedPacket.join(result, current);                

-        }

-    }

-

-    public void reset() {

-        result = null;

-        current.clear();

-    }

-

-    public int position() {

-        return current.position() + (result==null ? 0 : result.remaining());

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.activeio.packet.AppendedPacket;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+
+/**
+ *
+ */
+final public class PacketByteArrayOutputStream extends OutputStream {
+    
+    private Packet result;
+    private Packet current;
+    int nextAllocationSize=0;
+    
+    public PacketByteArrayOutputStream() {
+    	this( 1024 );
+    }
+    
+    public PacketByteArrayOutputStream(int initialSize) {
+    	nextAllocationSize = initialSize;
+        current = allocate();
+    }
+    
+    protected Packet allocate() {
+    	ByteArrayPacket packet = new ByteArrayPacket(new byte[nextAllocationSize]);
+    	nextAllocationSize <<= 3; // x by 8
+        return packet;
+    }
+    
+    public void skip(int size) {
+        while( size > 0 ) {
+            if( !current.hasRemaining() ) {
+                allocatedNext();
+            }
+            
+            int skip = ((size <= current.remaining()) ? size : current.remaining());
+            current.position(current.position()+skip);
+            size -= skip;
+        }
+    }
+    
+    public void write(int b) throws IOException {
+        if( !current.hasRemaining() ) {
+            allocatedNext();
+        }
+        current.write(b);
+    }
+    
+    public void write(byte[] b, int off, int len) throws IOException {
+        while( len > 0 ) {
+	        if( !current.hasRemaining() ) {
+	            allocatedNext();
+	        }
+	        int wrote = current.write(b,off,len);
+	        off+=wrote;
+	        len-=wrote;
+        }
+    }
+    
+    private void allocatedNext() {
+        if( result == null ) {
+            current.flip();
+            result = current;
+        } else {
+            current.flip();
+            result = AppendedPacket.join(result, current);            
+        }
+        current = allocate();
+    }
+    
+    public Packet getPacket() {
+        if( result == null ) {
+            current.flip();
+            return current.slice();
+        } else {
+            current.flip();
+            return AppendedPacket.join(result, current);                
+        }
+    }
+
+    public void reset() {
+        result = null;
+        current.clear();
+    }
+
+    public int position() {
+        return current.position() + (result==null ? 0 : result.remaining());
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/PacketOutputStream.java b/activeio-core/src/main/java/org/apache/activeio/adapter/PacketOutputStream.java
index 3315975..7dfb555 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/PacketOutputStream.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/PacketOutputStream.java
@@ -1,46 +1,46 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.OutputStream;

-

-import org.apache.activeio.packet.Packet;

-

-/**

- * Provides an OutputStream for a given Packet.

- *  

- * @version $Revision$

- */

-public class PacketOutputStream extends OutputStream {

-    

-    final Packet packet;

-    

-    public PacketOutputStream(Packet packet) {

-        this.packet = packet;

-    }

-

-    public void write(int b) throws IOException {

-        if( !packet.write(b) )

-            throw new IOException("Packet does not have any remaining space to write to.");

-    }

-    

-    public void write(byte[] b, int off, int len) throws IOException {

-        if( packet.write(b, off, len)!=len )

-            throw new IOException("Packet does not have "+len+" byte(s) left to write to.");

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.activeio.packet.Packet;
+
+/**
+ * Provides an OutputStream for a given Packet.
+ *  
+ * @version $Revision$
+ */
+public class PacketOutputStream extends OutputStream {
+    
+    final Packet packet;
+    
+    public PacketOutputStream(Packet packet) {
+        this.packet = packet;
+    }
+
+    public void write(int b) throws IOException {
+        if( !packet.write(b) )
+            throw new IOException("Packet does not have any remaining space to write to.");
+    }
+    
+    public void write(byte[] b, int off, int len) throws IOException {
+        if( packet.write(b, off, len)!=len )
+            throw new IOException("Packet does not have "+len+" byte(s) left to write to.");
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/PacketToInputStream.java b/activeio-core/src/main/java/org/apache/activeio/adapter/PacketToInputStream.java
index e1671ce..73982eb 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/PacketToInputStream.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/PacketToInputStream.java
@@ -1,54 +1,54 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.InputStream;

-

-import org.apache.activeio.packet.Packet;

-

-/**

- * Provides an InputStream for a given Packet.

- *  

- * @version $Revision$

- */

-public class PacketToInputStream extends InputStream {

-    

-    final Packet packet;

-    

-    /**

-     * @param packet

-     */

-    public PacketToInputStream(Packet packet) {

-        this.packet = packet;

-    }

-    

-    /**

-     * @see java.io.InputStream#read()

-     */

-    public int read() throws IOException {

-        return packet.read();

-    }

-

-    /**

-     * @see java.io.InputStream#read(byte[], int, int)

-     */

-    public int read(byte[] b, int off, int len) throws IOException {

-        return packet.read(b, off, len);

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.activeio.packet.Packet;
+
+/**
+ * Provides an InputStream for a given Packet.
+ *  
+ * @version $Revision$
+ */
+public class PacketToInputStream extends InputStream {
+    
+    final Packet packet;
+    
+    /**
+     * @param packet
+     */
+    public PacketToInputStream(Packet packet) {
+        this.packet = packet;
+    }
+    
+    /**
+     * @see java.io.InputStream#read()
+     */
+    public int read() throws IOException {
+        return packet.read();
+    }
+
+    /**
+     * @see java.io.InputStream#read(byte[], int, int)
+     */
+    public int read(byte[] b, int off, int len) throws IOException {
+        return packet.read(b, off, len);
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelServerToServerSocket.java b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelServerToServerSocket.java
index 017f034..45c82a6 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelServerToServerSocket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelServerToServerSocket.java
@@ -1,133 +1,133 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-import java.net.InetAddress;

-import java.net.InetSocketAddress;

-import java.net.ServerSocket;

-import java.net.Socket;

-import java.net.SocketAddress;

-import java.net.SocketException;

-import java.net.URI;

-import java.nio.channels.ServerSocketChannel;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-/**

- */

-public class SyncChannelServerToServerSocket extends ServerSocket {

-

-    private final SyncChannelServer channelServer;

-    private long timeout = Channel.WAIT_FOREVER_TIMEOUT;

-    boolean closed;

-    private InetAddress inetAddress;

-    private int localPort;

-    private SocketAddress localSocketAddress;

-    private int receiveBufferSize;

-    private boolean reuseAddress;

-    

-    /**

-     * @throws IOException

-     */

-    public SyncChannelServerToServerSocket(SyncChannelServer channelServer) throws IOException {

-        this.channelServer = channelServer;

-        URI connectURI = channelServer.getConnectURI();

-        localPort = connectURI.getPort();

-        inetAddress = InetAddress.getByName(connectURI.getHost());

-        localSocketAddress = new InetSocketAddress(inetAddress, localPort);        

-    }

-    

-    public synchronized void setSoTimeout(int timeout) throws SocketException {

-        if( timeout <= 0 )

-            this.timeout = Channel.WAIT_FOREVER_TIMEOUT;

-        else 

-            this.timeout = timeout;

-    }

-    

-    public synchronized int getSoTimeout() throws IOException {

-        if( timeout == Channel.WAIT_FOREVER_TIMEOUT )

-            return 0;

-        return (int) timeout;

-    }

-

-    public Socket accept() throws IOException {

-        Channel channel = channelServer.accept(timeout);

-        if( channel==null )

-            throw new InterruptedIOException();

-        

-        SyncChannel syncChannel = AsyncToSyncChannel.adapt(channel);            

-        syncChannel.start();

-        return new SyncChannelToSocket(syncChannel);

-                    

-    }

-    

-    public void bind(SocketAddress endpoint, int backlog) throws IOException {

-    	if (isClosed())

-    	    throw new SocketException("Socket is closed");

-  	    throw new SocketException("Already bound");

-    }

-    

-    public void bind(SocketAddress endpoint) throws IOException {

-    	if (isClosed())

-    	    throw new SocketException("Socket is closed");

-  	    throw new SocketException("Already bound");

-    }

-    

-    public ServerSocketChannel getChannel() {

-        return null;

-    }

-    

-    public InetAddress getInetAddress() {

-        return inetAddress;

-    }

-    public int getLocalPort() {

-        return localPort;

-    }

-    public SocketAddress getLocalSocketAddress() {

-        return localSocketAddress;

-    }    

-    public synchronized int getReceiveBufferSize() throws SocketException {

-        return receiveBufferSize;

-    }

-    

-    public boolean getReuseAddress() throws SocketException {

-        return reuseAddress;

-    }

-    

-    public boolean isBound() {

-        return true;

-    }

-    

-    public boolean isClosed() {

-        return closed;

-    }

-    

-    public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {

-    }

-    

-    public synchronized void setReceiveBufferSize(int size) throws SocketException {

-        this.receiveBufferSize = size;

-    }

-    

-    public void setReuseAddress(boolean on) throws SocketException {

-        reuseAddress = on;

-    }    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.URI;
+import java.nio.channels.ServerSocketChannel;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+/**
+ */
+public class SyncChannelServerToServerSocket extends ServerSocket {
+
+    private final SyncChannelServer channelServer;
+    private long timeout = Channel.WAIT_FOREVER_TIMEOUT;
+    boolean closed;
+    private InetAddress inetAddress;
+    private int localPort;
+    private SocketAddress localSocketAddress;
+    private int receiveBufferSize;
+    private boolean reuseAddress;
+    
+    /**
+     * @throws IOException
+     */
+    public SyncChannelServerToServerSocket(SyncChannelServer channelServer) throws IOException {
+        this.channelServer = channelServer;
+        URI connectURI = channelServer.getConnectURI();
+        localPort = connectURI.getPort();
+        inetAddress = InetAddress.getByName(connectURI.getHost());
+        localSocketAddress = new InetSocketAddress(inetAddress, localPort);        
+    }
+    
+    public synchronized void setSoTimeout(int timeout) throws SocketException {
+        if( timeout <= 0 )
+            this.timeout = Channel.WAIT_FOREVER_TIMEOUT;
+        else 
+            this.timeout = timeout;
+    }
+    
+    public synchronized int getSoTimeout() throws IOException {
+        if( timeout == Channel.WAIT_FOREVER_TIMEOUT )
+            return 0;
+        return (int) timeout;
+    }
+
+    public Socket accept() throws IOException {
+        Channel channel = channelServer.accept(timeout);
+        if( channel==null )
+            throw new InterruptedIOException();
+        
+        SyncChannel syncChannel = AsyncToSyncChannel.adapt(channel);            
+        syncChannel.start();
+        return new SyncChannelToSocket(syncChannel);
+                    
+    }
+    
+    public void bind(SocketAddress endpoint, int backlog) throws IOException {
+    	if (isClosed())
+    	    throw new SocketException("Socket is closed");
+  	    throw new SocketException("Already bound");
+    }
+    
+    public void bind(SocketAddress endpoint) throws IOException {
+    	if (isClosed())
+    	    throw new SocketException("Socket is closed");
+  	    throw new SocketException("Already bound");
+    }
+    
+    public ServerSocketChannel getChannel() {
+        return null;
+    }
+    
+    public InetAddress getInetAddress() {
+        return inetAddress;
+    }
+    public int getLocalPort() {
+        return localPort;
+    }
+    public SocketAddress getLocalSocketAddress() {
+        return localSocketAddress;
+    }    
+    public synchronized int getReceiveBufferSize() throws SocketException {
+        return receiveBufferSize;
+    }
+    
+    public boolean getReuseAddress() throws SocketException {
+        return reuseAddress;
+    }
+    
+    public boolean isBound() {
+        return true;
+    }
+    
+    public boolean isClosed() {
+        return closed;
+    }
+    
+    public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
+    }
+    
+    public synchronized void setReceiveBufferSize(int size) throws SocketException {
+        this.receiveBufferSize = size;
+    }
+    
+    public void setReuseAddress(boolean on) throws SocketException {
+        reuseAddress = on;
+    }    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToInputStream.java b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToInputStream.java
index b3fe6d8..427b3af 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToInputStream.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToInputStream.java
@@ -1,114 +1,114 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.InputStream;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.SyncChannel;

-

-/**

- * Provides an InputStream for a given SynchChannel.

- *  

- * @version $Revision$

- */

-public class SyncChannelToInputStream extends InputStream {

-    

-    private final SyncChannel channel;

-    private Packet lastPacket;

-    private boolean closed;

-    private long timeout = Channel.WAIT_FOREVER_TIMEOUT;

-    

-    /**

-     * @param channel

-     */

-    public SyncChannelToInputStream(final SyncChannel channel) {

-        this.channel = channel;

-    }

-    

-    /**

-     * @see java.io.InputStream#read()

-     */

-    public int read() throws IOException {

-        while( true ) {

-            if( lastPacket==null ) {

-                try {

-                    lastPacket = channel.read(timeout);

-                } catch (IOException e) {

-                    throw (IOException)new IOException("Channel failed: "+e.getMessage()).initCause(e);

-                }

-            }

-            if( lastPacket.hasRemaining() ) {

-                return lastPacket.read();

-            }

-        }

-    }

-

-    /**

-     * @see java.io.InputStream#read(byte[], int, int)

-     */

-    public int read(byte[] b, int off, int len) throws IOException {

-        while( true ) {

-            if( lastPacket==null || !lastPacket.hasRemaining() ) {

-                try {

-                    lastPacket = channel.read(timeout);

-                } catch (IOException e) {

-                    throw (IOException)new IOException("Channel failed: "+e.getMessage()).initCause(e);

-                }

-            }

-            if( lastPacket==EOSPacket.EOS_PACKET ) {

-                return -1;

-            }

-            if( lastPacket!=null && lastPacket.hasRemaining() ) {

-                return lastPacket.read(b, off, len);

-            }

-        }

-    }

- 

-    /**

-     * @see java.io.InputStream#close()

-     */

-    public void close() throws IOException {

-        closed=true;

-        super.close();

-    }

-    

-    public boolean isClosed() {

-        return closed;

-    }

-

-    /**

-     * @param timeout

-     */

-    public void setTimeout(long timeout) {

-        if( timeout <= 0 )

-            timeout = Channel.WAIT_FOREVER_TIMEOUT;

-        this.timeout = timeout;

-    }

-

-    /**

-     * @return

-     */

-    public long getTimeout() {

-        if( timeout == Channel.WAIT_FOREVER_TIMEOUT )

-            return 0;

-        return timeout;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.SyncChannel;
+
+/**
+ * Provides an InputStream for a given SynchChannel.
+ *  
+ * @version $Revision$
+ */
+public class SyncChannelToInputStream extends InputStream {
+    
+    private final SyncChannel channel;
+    private Packet lastPacket;
+    private boolean closed;
+    private long timeout = Channel.WAIT_FOREVER_TIMEOUT;
+    
+    /**
+     * @param channel
+     */
+    public SyncChannelToInputStream(final SyncChannel channel) {
+        this.channel = channel;
+    }
+    
+    /**
+     * @see java.io.InputStream#read()
+     */
+    public int read() throws IOException {
+        while( true ) {
+            if( lastPacket==null ) {
+                try {
+                    lastPacket = channel.read(timeout);
+                } catch (IOException e) {
+                    throw (IOException)new IOException("Channel failed: "+e.getMessage()).initCause(e);
+                }
+            }
+            if( lastPacket.hasRemaining() ) {
+                return lastPacket.read();
+            }
+        }
+    }
+
+    /**
+     * @see java.io.InputStream#read(byte[], int, int)
+     */
+    public int read(byte[] b, int off, int len) throws IOException {
+        while( true ) {
+            if( lastPacket==null || !lastPacket.hasRemaining() ) {
+                try {
+                    lastPacket = channel.read(timeout);
+                } catch (IOException e) {
+                    throw (IOException)new IOException("Channel failed: "+e.getMessage()).initCause(e);
+                }
+            }
+            if( lastPacket==EOSPacket.EOS_PACKET ) {
+                return -1;
+            }
+            if( lastPacket!=null && lastPacket.hasRemaining() ) {
+                return lastPacket.read(b, off, len);
+            }
+        }
+    }
+ 
+    /**
+     * @see java.io.InputStream#close()
+     */
+    public void close() throws IOException {
+        closed=true;
+        super.close();
+    }
+    
+    public boolean isClosed() {
+        return closed;
+    }
+
+    /**
+     * @param timeout
+     */
+    public void setTimeout(long timeout) {
+        if( timeout <= 0 )
+            timeout = Channel.WAIT_FOREVER_TIMEOUT;
+        this.timeout = timeout;
+    }
+
+    /**
+     * @return
+     */
+    public long getTimeout() {
+        if( timeout == Channel.WAIT_FOREVER_TIMEOUT )
+            return 0;
+        return timeout;
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToOutputStream.java b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToOutputStream.java
index 1055d4d..45f3cc6 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToOutputStream.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToOutputStream.java
@@ -1,72 +1,72 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.OutputStream;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.BytePacket;

-import org.apache.activeio.packet.sync.SyncChannel;

-

-/**

- */

-public class SyncChannelToOutputStream extends OutputStream {

-

-    private final SyncChannel channel;

-    private boolean closed;

-

-    /**

-     * @param channel

-     */

-    public SyncChannelToOutputStream(SyncChannel channel) {

-        this.channel = channel;

-    }

-

-    /**

-     * @see java.io.OutputStream#write(int)

-     */

-    public void write(int b) throws IOException {

-        channel.write(new BytePacket((byte) b));

-    }

-

-    /**

-     * @see java.io.OutputStream#write(byte[], int, int)

-     */

-    public void write(byte[] b, int off, int len) throws IOException {

-        channel.write(new ByteArrayPacket(b, off, len));

-    }

-    

-    /**

-     * @see java.io.OutputStream#flush()

-     */

-    public void flush() throws IOException {

-        channel.flush();

-    }

-            

-    /**

-     * @see java.io.InputStream#close()

-     */

-    public void close() throws IOException {

-        closed=true;

-        super.close();

-    }

-    

-    public boolean isClosed() {

-        return closed;

-    }    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.BytePacket;
+import org.apache.activeio.packet.sync.SyncChannel;
+
+/**
+ */
+public class SyncChannelToOutputStream extends OutputStream {
+
+    private final SyncChannel channel;
+    private boolean closed;
+
+    /**
+     * @param channel
+     */
+    public SyncChannelToOutputStream(SyncChannel channel) {
+        this.channel = channel;
+    }
+
+    /**
+     * @see java.io.OutputStream#write(int)
+     */
+    public void write(int b) throws IOException {
+        channel.write(new BytePacket((byte) b));
+    }
+
+    /**
+     * @see java.io.OutputStream#write(byte[], int, int)
+     */
+    public void write(byte[] b, int off, int len) throws IOException {
+        channel.write(new ByteArrayPacket(b, off, len));
+    }
+    
+    /**
+     * @see java.io.OutputStream#flush()
+     */
+    public void flush() throws IOException {
+        channel.flush();
+    }
+            
+    /**
+     * @see java.io.InputStream#close()
+     */
+    public void close() throws IOException {
+        closed=true;
+        super.close();
+    }
+    
+    public boolean isClosed() {
+        return closed;
+    }    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToSocket.java b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToSocket.java
index d938527..ff21385 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToSocket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncChannelToSocket.java
@@ -1,221 +1,221 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.io.InputStream;

-import java.io.OutputStream;

-import java.net.InetAddress;

-import java.net.Socket;

-import java.net.SocketAddress;

-import java.net.SocketException;

-import java.nio.channels.SocketChannel;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.stream.sync.socket.SocketMetadata;

-

-/**

- * Provides a {@see java.net.Socket} interface to a {@see org.apache.activeio.SynchChannel}.

- * 

- * If the {@see org.apache.activeio.SynchChannel} being adapted can not be 

- * {@see org.apache.activeio.Channel#narrow(Class)}ed to a {@see org.apache.activeio.net.SocketMetadata} 

- * then all methods accessing socket metadata will throw a {@see java.net.SocketException}.

- *  

- */

-public class SyncChannelToSocket extends Socket {

-    

-    private final SyncChannel channel;

-    private final SyncChannelToInputStream inputStream;

-    private final SyncChannelToOutputStream outputStream;

-    private final SocketMetadata socketMetadata;

-    private final Packet urgentPackget = new ByteArrayPacket(new byte[1]);

-    boolean closed;

-

-    public SyncChannelToSocket(SyncChannel channel) {

-        this(channel, (SocketMetadata)channel.getAdapter(SocketMetadata.class));

-    }

-    

-    public SyncChannelToSocket(SyncChannel channel, SocketMetadata socketMetadata) {

-        this.channel = channel;

-        this.socketMetadata = socketMetadata;

-        this.inputStream = new SyncChannelToInputStream(channel);

-        this.outputStream = new SyncChannelToOutputStream(channel);

-    }

-

-    public boolean isConnected() {

-        return true;

-    }

-    

-    public boolean isBound() {

-        return true;

-    }

-    

-    public boolean isClosed() {

-        return closed;

-    }

-

-    public void bind(SocketAddress bindpoint) throws IOException {

-        throw new IOException("Not supported");

-    }

-

-    public synchronized void close() throws IOException {

-        if( closed )

-            return;

-        closed = true;

-        inputStream.close();

-        outputStream.close();

-        channel.stop();

-    }

-    

-    public void connect(SocketAddress endpoint) throws IOException {

-        throw new IOException("Not supported");

-    }

-    

-    public void connect(SocketAddress endpoint, int timeout) throws IOException {

-        throw new IOException("Not supported");

-    }

-

-    public SocketChannel getChannel() {

-        return null;

-    }

-    

-    public InputStream getInputStream() throws IOException {

-        return inputStream;

-    }

-

-    public OutputStream getOutputStream() throws IOException {

-        return outputStream;

-    }

-    

-    public boolean isInputShutdown() {

-        return inputStream.isClosed();

-    }

-

-    public boolean isOutputShutdown() {

-        return outputStream.isClosed();

-    }

-    

-    public void sendUrgentData(int data) throws IOException {

-        urgentPackget.clear();

-        urgentPackget.write(data);

-        urgentPackget.flip();

-        channel.write(urgentPackget);

-    }

-

-    public int getSoTimeout() throws SocketException {

-        return (int) inputStream.getTimeout();

-    }

-    

-    public synchronized void setSoTimeout(int timeout) throws SocketException {

-        inputStream.setTimeout(timeout);

-    }    

-    

-    public void shutdownOutput() throws IOException {

-        outputStream.close();

-    }

-    

-    public void shutdownInput() throws IOException {

-        inputStream.close();

-    }

-    

-    protected SocketMetadata getSocketMetadata() throws SocketException {

-        if( socketMetadata == null )

-            throw new SocketException("No socket metadata available.");

-        return socketMetadata;

-    }

-    

-    public InetAddress getInetAddress() {

-        if( socketMetadata ==null )

-            return null;

-        return socketMetadata.getInetAddress();

-    }

-    public boolean getKeepAlive() throws SocketException {

-        return getSocketMetadata().getKeepAlive();

-    }

-    public InetAddress getLocalAddress() {

-        if( socketMetadata ==null )

-            return null;

-        return socketMetadata.getLocalAddress();

-    }

-    public int getLocalPort() {

-        if( socketMetadata ==null )

-            return -1;

-        return socketMetadata.getLocalPort();

-    }

-    public SocketAddress getLocalSocketAddress() {

-        if( socketMetadata ==null )

-            return null;

-        return socketMetadata.getLocalSocketAddress();

-    }

-    public boolean getOOBInline() throws SocketException {

-        return getSocketMetadata().getOOBInline();

-    }

-    public int getPort() {

-        if( socketMetadata ==null )

-            return -1;

-        return socketMetadata.getPort();

-    }

-    public int getReceiveBufferSize() throws SocketException {

-        return getSocketMetadata().getReceiveBufferSize();

-    }

-    public SocketAddress getRemoteSocketAddress() {

-        if( socketMetadata ==null )

-            return null;

-        return socketMetadata.getRemoteSocketAddress();

-    }

-    public boolean getReuseAddress() throws SocketException {

-        return getSocketMetadata().getReuseAddress();

-    }

-    public int getSendBufferSize() throws SocketException {

-        return getSocketMetadata().getSendBufferSize();

-    }

-    public int getSoLinger() throws SocketException {

-        return getSocketMetadata().getSoLinger();

-    }

-    public boolean getTcpNoDelay() throws SocketException {

-        return getSocketMetadata().getTcpNoDelay();

-    }

-    public int getTrafficClass() throws SocketException {

-        return getSocketMetadata().getTrafficClass();

-    }

-    public void setKeepAlive(boolean on) throws SocketException {

-        getSocketMetadata().setKeepAlive(on);

-    }

-    public void setOOBInline(boolean on) throws SocketException {

-        getSocketMetadata().setOOBInline(on);

-    }

-    public void setReceiveBufferSize(int size) throws SocketException {

-        getSocketMetadata().setReceiveBufferSize(size);

-    }

-    public void setReuseAddress(boolean on) throws SocketException {

-        getSocketMetadata().setReuseAddress(on);

-    }

-    public void setSendBufferSize(int size) throws SocketException {

-        getSocketMetadata().setSendBufferSize(size);

-    }

-    public void setSoLinger(boolean on, int linger) throws SocketException {

-        getSocketMetadata().setSoLinger(on, linger);

-    }

-    public void setTcpNoDelay(boolean on) throws SocketException {

-        getSocketMetadata().setTcpNoDelay(on);

-    }

-    public void setTrafficClass(int tc) throws SocketException {

-        getSocketMetadata().setTrafficClass(tc);

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.nio.channels.SocketChannel;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.stream.sync.socket.SocketMetadata;
+
+/**
+ * Provides a {@see java.net.Socket} interface to a {@see org.apache.activeio.SynchChannel}.
+ * 
+ * If the {@see org.apache.activeio.SynchChannel} being adapted can not be 
+ * {@see org.apache.activeio.Channel#narrow(Class)}ed to a {@see org.apache.activeio.net.SocketMetadata} 
+ * then all methods accessing socket metadata will throw a {@see java.net.SocketException}.
+ *  
+ */
+public class SyncChannelToSocket extends Socket {
+    
+    private final SyncChannel channel;
+    private final SyncChannelToInputStream inputStream;
+    private final SyncChannelToOutputStream outputStream;
+    private final SocketMetadata socketMetadata;
+    private final Packet urgentPackget = new ByteArrayPacket(new byte[1]);
+    boolean closed;
+
+    public SyncChannelToSocket(SyncChannel channel) {
+        this(channel, (SocketMetadata)channel.getAdapter(SocketMetadata.class));
+    }
+    
+    public SyncChannelToSocket(SyncChannel channel, SocketMetadata socketMetadata) {
+        this.channel = channel;
+        this.socketMetadata = socketMetadata;
+        this.inputStream = new SyncChannelToInputStream(channel);
+        this.outputStream = new SyncChannelToOutputStream(channel);
+    }
+
+    public boolean isConnected() {
+        return true;
+    }
+    
+    public boolean isBound() {
+        return true;
+    }
+    
+    public boolean isClosed() {
+        return closed;
+    }
+
+    public void bind(SocketAddress bindpoint) throws IOException {
+        throw new IOException("Not supported");
+    }
+
+    public synchronized void close() throws IOException {
+        if( closed )
+            return;
+        closed = true;
+        inputStream.close();
+        outputStream.close();
+        channel.stop();
+    }
+    
+    public void connect(SocketAddress endpoint) throws IOException {
+        throw new IOException("Not supported");
+    }
+    
+    public void connect(SocketAddress endpoint, int timeout) throws IOException {
+        throw new IOException("Not supported");
+    }
+
+    public SocketChannel getChannel() {
+        return null;
+    }
+    
+    public InputStream getInputStream() throws IOException {
+        return inputStream;
+    }
+
+    public OutputStream getOutputStream() throws IOException {
+        return outputStream;
+    }
+    
+    public boolean isInputShutdown() {
+        return inputStream.isClosed();
+    }
+
+    public boolean isOutputShutdown() {
+        return outputStream.isClosed();
+    }
+    
+    public void sendUrgentData(int data) throws IOException {
+        urgentPackget.clear();
+        urgentPackget.write(data);
+        urgentPackget.flip();
+        channel.write(urgentPackget);
+    }
+
+    public int getSoTimeout() throws SocketException {
+        return (int) inputStream.getTimeout();
+    }
+    
+    public synchronized void setSoTimeout(int timeout) throws SocketException {
+        inputStream.setTimeout(timeout);
+    }    
+    
+    public void shutdownOutput() throws IOException {
+        outputStream.close();
+    }
+    
+    public void shutdownInput() throws IOException {
+        inputStream.close();
+    }
+    
+    protected SocketMetadata getSocketMetadata() throws SocketException {
+        if( socketMetadata == null )
+            throw new SocketException("No socket metadata available.");
+        return socketMetadata;
+    }
+    
+    public InetAddress getInetAddress() {
+        if( socketMetadata ==null )
+            return null;
+        return socketMetadata.getInetAddress();
+    }
+    public boolean getKeepAlive() throws SocketException {
+        return getSocketMetadata().getKeepAlive();
+    }
+    public InetAddress getLocalAddress() {
+        if( socketMetadata ==null )
+            return null;
+        return socketMetadata.getLocalAddress();
+    }
+    public int getLocalPort() {
+        if( socketMetadata ==null )
+            return -1;
+        return socketMetadata.getLocalPort();
+    }
+    public SocketAddress getLocalSocketAddress() {
+        if( socketMetadata ==null )
+            return null;
+        return socketMetadata.getLocalSocketAddress();
+    }
+    public boolean getOOBInline() throws SocketException {
+        return getSocketMetadata().getOOBInline();
+    }
+    public int getPort() {
+        if( socketMetadata ==null )
+            return -1;
+        return socketMetadata.getPort();
+    }
+    public int getReceiveBufferSize() throws SocketException {
+        return getSocketMetadata().getReceiveBufferSize();
+    }
+    public SocketAddress getRemoteSocketAddress() {
+        if( socketMetadata ==null )
+            return null;
+        return socketMetadata.getRemoteSocketAddress();
+    }
+    public boolean getReuseAddress() throws SocketException {
+        return getSocketMetadata().getReuseAddress();
+    }
+    public int getSendBufferSize() throws SocketException {
+        return getSocketMetadata().getSendBufferSize();
+    }
+    public int getSoLinger() throws SocketException {
+        return getSocketMetadata().getSoLinger();
+    }
+    public boolean getTcpNoDelay() throws SocketException {
+        return getSocketMetadata().getTcpNoDelay();
+    }
+    public int getTrafficClass() throws SocketException {
+        return getSocketMetadata().getTrafficClass();
+    }
+    public void setKeepAlive(boolean on) throws SocketException {
+        getSocketMetadata().setKeepAlive(on);
+    }
+    public void setOOBInline(boolean on) throws SocketException {
+        getSocketMetadata().setOOBInline(on);
+    }
+    public void setReceiveBufferSize(int size) throws SocketException {
+        getSocketMetadata().setReceiveBufferSize(size);
+    }
+    public void setReuseAddress(boolean on) throws SocketException {
+        getSocketMetadata().setReuseAddress(on);
+    }
+    public void setSendBufferSize(int size) throws SocketException {
+        getSocketMetadata().setSendBufferSize(size);
+    }
+    public void setSoLinger(boolean on, int linger) throws SocketException {
+        getSocketMetadata().setSoLinger(on, linger);
+    }
+    public void setTcpNoDelay(boolean on) throws SocketException {
+        getSocketMetadata().setTcpNoDelay(on);
+    }
+    public void setTrafficClass(int tc) throws SocketException {
+        getSocketMetadata().setTrafficClass(tc);
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannel.java
index 8cacbd2..f529569 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannel.java
@@ -1,200 +1,200 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;

-import edu.emory.mathcs.backport.java.util.concurrent.Executor;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelFactory;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelListener;

-import org.apache.activeio.packet.sync.SyncChannel;

-

-import java.io.IOException;

-

-/**

- * Adapts a {@see org.apache.activeio.SynchChannel} so that it provides an 

- * {@see org.apache.activeio.AsyncChannel} interface.  When this channel

- * is started, a background thread is used to poll the {@see org.apache.activeio.SynchChannel}

- *  for packets comming up the channel which are then delivered to the 

- * {@see org.apache.activeio.ChannelConsumer}.

- * 

- * @version $Revision$

- */

-public class SyncToAsyncChannel implements AsyncChannel, Runnable {

-

-    private final AtomicBoolean running = new AtomicBoolean(false);

-    private final SyncChannel syncChannel;

-    private final Executor executor;

-    private AsyncChannelListener channelListener;

-    private CountDownLatch doneCountDownLatch;

-    

-    

-    static public AsyncChannel adapt(Channel channel) {

-        return adapt(channel, ChannelFactory.DEFAULT_EXECUTOR);

-    }

-

-    static public AsyncChannel adapt(Channel channel, Executor executor) {

-        

-        // It might not need adapting

-        if( channel instanceof AsyncChannel ) {

-            return (AsyncChannel) channel;

-        }

-        

-        // Can we just just undo the adaptor

-        if( channel.getClass() == SyncToAsyncChannel.class ) {

-            return ((AsyncToSyncChannel)channel).getAsyncChannel();

-        }

-        

-        return new SyncToAsyncChannel((SyncChannel) channel, executor);

-        

-    }

-

-    

-    /**

-     * @deprecated {@see #adapt(SynchChannel)}

-     */

-    public SyncToAsyncChannel(SyncChannel syncChannel) {

-        this(syncChannel, ChannelFactory.DEFAULT_EXECUTOR);

-    }

-

-    /**

-     * @deprecated {@see #adapt(SynchChannel, Executor)}

-     */

-    public SyncToAsyncChannel(SyncChannel syncChannel, Executor executor) {

-        this.syncChannel = syncChannel;

-        this.executor = executor;

-    }

-

-    synchronized public void start() throws IOException {

-        if (running.compareAndSet(false, true)) {

-            

-            if (channelListener == null)

-                throw new IllegalStateException("UpPacketListener must be set before object can be started.");

-            

-            syncChannel.start();

-

-            doneCountDownLatch = new CountDownLatch(1);

-            executor.execute(this);

-        }

-    }

-

-    synchronized public void stop() throws IOException {

-        if (running.compareAndSet(true, false)) {

-            try {

-                doneCountDownLatch.await(5, TimeUnit.SECONDS);

-            } catch (Throwable e) {

-            }

-            syncChannel.stop();

-        }

-    }

-

-    /**

-     * reads packets from a Socket

-     */

-    public void run() {

-        

-        // Change the thread name.

-        String oldName = Thread.currentThread().getName();        

-        Thread.currentThread().setName( syncChannel.toString() );        

-        try {

-	        while (running.get()) {

-	            try {

-	                Packet packet = syncChannel.read(500);

-	                if( packet==null )

-	                    continue;    

-                    

-                    if( packet == EOSPacket.EOS_PACKET ) {

-                        channelListener.onPacket(packet);

-                        return;

-                    }

-                    

-                    if( packet.hasRemaining() ) {

-                        channelListener.onPacket(packet);

-                    }

-                    

-	            } catch (IOException e) {

-	                channelListener.onPacketError(e);

-	            } catch (Throwable e) {

-	                channelListener.onPacketError((IOException)new IOException("Unexpected Error: "+e).initCause(e));

-	            }

-	        }

-        } finally {

-            if( doneCountDownLatch!=null )

-                doneCountDownLatch.countDown();

-            Thread.currentThread().setName(oldName);

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.AsyncChannel#setAsyncChannelListener(org.apache.activeio.UpPacketListener)

-     */

-    public void setAsyncChannelListener(AsyncChannelListener channelListener) {

-        if (running.get())

-            throw new IllegalStateException("Cannot change the UpPacketListener while the object is running.");

-        this.channelListener = channelListener;

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)

-     */

-    public void write(org.apache.activeio.packet.Packet packet) throws IOException {

-        syncChannel.write(packet);

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#flush()

-     */

-    public void flush() throws IOException {

-        syncChannel.flush();

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        try {

-            stop();

-        } catch ( IOException ignore) {

-        }

-        syncChannel.dispose();        

-    }

-

-    public AsyncChannelListener getAsyncChannelListener() {

-        return channelListener;

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return syncChannel.getAdapter(target);

-    }    

-    

-    public SyncChannel getSynchChannel() {

-        return syncChannel;

-    }

-

-    public String toString() {

-        return syncChannel.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
+import edu.emory.mathcs.backport.java.util.concurrent.Executor;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelFactory;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelListener;
+import org.apache.activeio.packet.sync.SyncChannel;
+
+import java.io.IOException;
+
+/**
+ * Adapts a {@see org.apache.activeio.SynchChannel} so that it provides an 
+ * {@see org.apache.activeio.AsyncChannel} interface.  When this channel
+ * is started, a background thread is used to poll the {@see org.apache.activeio.SynchChannel}
+ *  for packets comming up the channel which are then delivered to the 
+ * {@see org.apache.activeio.ChannelConsumer}.
+ * 
+ * @version $Revision$
+ */
+public class SyncToAsyncChannel implements AsyncChannel, Runnable {
+
+    private final AtomicBoolean running = new AtomicBoolean(false);
+    private final SyncChannel syncChannel;
+    private final Executor executor;
+    private AsyncChannelListener channelListener;
+    private CountDownLatch doneCountDownLatch;
+    
+    
+    static public AsyncChannel adapt(Channel channel) {
+        return adapt(channel, ChannelFactory.DEFAULT_EXECUTOR);
+    }
+
+    static public AsyncChannel adapt(Channel channel, Executor executor) {
+        
+        // It might not need adapting
+        if( channel instanceof AsyncChannel ) {
+            return (AsyncChannel) channel;
+        }
+        
+        // Can we just just undo the adaptor
+        if( channel.getClass() == SyncToAsyncChannel.class ) {
+            return ((AsyncToSyncChannel)channel).getAsyncChannel();
+        }
+        
+        return new SyncToAsyncChannel((SyncChannel) channel, executor);
+        
+    }
+
+    
+    /**
+     * @deprecated {@see #adapt(SynchChannel)}
+     */
+    public SyncToAsyncChannel(SyncChannel syncChannel) {
+        this(syncChannel, ChannelFactory.DEFAULT_EXECUTOR);
+    }
+
+    /**
+     * @deprecated {@see #adapt(SynchChannel, Executor)}
+     */
+    public SyncToAsyncChannel(SyncChannel syncChannel, Executor executor) {
+        this.syncChannel = syncChannel;
+        this.executor = executor;
+    }
+
+    synchronized public void start() throws IOException {
+        if (running.compareAndSet(false, true)) {
+            
+            if (channelListener == null)
+                throw new IllegalStateException("UpPacketListener must be set before object can be started.");
+            
+            syncChannel.start();
+
+            doneCountDownLatch = new CountDownLatch(1);
+            executor.execute(this);
+        }
+    }
+
+    synchronized public void stop() throws IOException {
+        if (running.compareAndSet(true, false)) {
+            try {
+                doneCountDownLatch.await(5, TimeUnit.SECONDS);
+            } catch (Throwable e) {
+            }
+            syncChannel.stop();
+        }
+    }
+
+    /**
+     * reads packets from a Socket
+     */
+    public void run() {
+        
+        // Change the thread name.
+        String oldName = Thread.currentThread().getName();        
+        Thread.currentThread().setName( syncChannel.toString() );        
+        try {
+	        while (running.get()) {
+	            try {
+	                Packet packet = syncChannel.read(500);
+	                if( packet==null )
+	                    continue;    
+                    
+                    if( packet == EOSPacket.EOS_PACKET ) {
+                        channelListener.onPacket(packet);
+                        return;
+                    }
+                    
+                    if( packet.hasRemaining() ) {
+                        channelListener.onPacket(packet);
+                    }
+                    
+	            } catch (IOException e) {
+	                channelListener.onPacketError(e);
+	            } catch (Throwable e) {
+	                channelListener.onPacketError((IOException)new IOException("Unexpected Error: "+e).initCause(e));
+	            }
+	        }
+        } finally {
+            if( doneCountDownLatch!=null )
+                doneCountDownLatch.countDown();
+            Thread.currentThread().setName(oldName);
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.AsyncChannel#setAsyncChannelListener(org.apache.activeio.UpPacketListener)
+     */
+    public void setAsyncChannelListener(AsyncChannelListener channelListener) {
+        if (running.get())
+            throw new IllegalStateException("Cannot change the UpPacketListener while the object is running.");
+        this.channelListener = channelListener;
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)
+     */
+    public void write(org.apache.activeio.packet.Packet packet) throws IOException {
+        syncChannel.write(packet);
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#flush()
+     */
+    public void flush() throws IOException {
+        syncChannel.flush();
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        try {
+            stop();
+        } catch ( IOException ignore) {
+        }
+        syncChannel.dispose();        
+    }
+
+    public AsyncChannelListener getAsyncChannelListener() {
+        return channelListener;
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return syncChannel.getAdapter(target);
+    }    
+    
+    public SyncChannel getSynchChannel() {
+        return syncChannel;
+    }
+
+    public String toString() {
+        return syncChannel.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelFactory.java
index a486bc2..b93813e 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelFactory.java
@@ -1,83 +1,83 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.ChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelFactory;

-

-import edu.emory.mathcs.backport.java.util.concurrent.Executor;

-

-/**

- * @version $Revision$

- */

-public class SyncToAsyncChannelFactory implements AsyncChannelFactory {

-    

-    private final SyncChannelFactory syncChannelFactory;

-    private final Executor executor;

-        

-    static public AsyncChannelFactory adapt(SyncChannelFactory channelFactory) {

-        return adapt(channelFactory, ChannelFactory.DEFAULT_EXECUTOR);

-    }

-    

-    static public AsyncChannelFactory adapt(SyncChannelFactory channelFactory, Executor executor ) {

-

-        // It might not need adapting

-        if( channelFactory instanceof AsyncChannelFactory ) {

-            return (AsyncChannelFactory) channelFactory;

-        }

-

-        // Can we just just undo the adaptor

-        if( channelFactory.getClass() == AsyncToSyncChannelFactory.class ) {

-            return ((AsyncToSyncChannelFactory)channelFactory).getAsyncChannelFactory();

-        }

-        

-        return new SyncToAsyncChannelFactory((SyncChannelFactory)channelFactory, executor);        

-    }

-    

-    /**

-     * @deprecated {@see #adapt(SyncChannelFactory)}

-     */

-    public SyncToAsyncChannelFactory(final SyncChannelFactory next) {

-        this(next, ChannelFactory.DEFAULT_EXECUTOR);

-    }

-    

-    /**

-     * @deprecated {@see #adapt(SyncChannelFactory, Executor)}

-     */

-    public SyncToAsyncChannelFactory(final SyncChannelFactory next, Executor executor) {

-        this.syncChannelFactory = next;

-        this.executor = executor;

-    }

-        

-    public AsyncChannel openAsyncChannel(URI location) throws IOException {

-        return SyncToAsyncChannel.adapt(syncChannelFactory.openSyncChannel(location),executor);

-    }

-

-    public AsyncChannelServer bindAsyncChannel(URI location) throws IOException {

-        return new SyncToAsyncChannelServer(syncChannelFactory.bindSyncChannel(location),executor);

-    }

-    

-    public SyncChannelFactory getSyncChannelFactory() {

-        return syncChannelFactory;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.ChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelFactory;
+
+import edu.emory.mathcs.backport.java.util.concurrent.Executor;
+
+/**
+ * @version $Revision$
+ */
+public class SyncToAsyncChannelFactory implements AsyncChannelFactory {
+    
+    private final SyncChannelFactory syncChannelFactory;
+    private final Executor executor;
+        
+    static public AsyncChannelFactory adapt(SyncChannelFactory channelFactory) {
+        return adapt(channelFactory, ChannelFactory.DEFAULT_EXECUTOR);
+    }
+    
+    static public AsyncChannelFactory adapt(SyncChannelFactory channelFactory, Executor executor ) {
+
+        // It might not need adapting
+        if( channelFactory instanceof AsyncChannelFactory ) {
+            return (AsyncChannelFactory) channelFactory;
+        }
+
+        // Can we just just undo the adaptor
+        if( channelFactory.getClass() == AsyncToSyncChannelFactory.class ) {
+            return ((AsyncToSyncChannelFactory)channelFactory).getAsyncChannelFactory();
+        }
+        
+        return new SyncToAsyncChannelFactory((SyncChannelFactory)channelFactory, executor);        
+    }
+    
+    /**
+     * @deprecated {@see #adapt(SyncChannelFactory)}
+     */
+    public SyncToAsyncChannelFactory(final SyncChannelFactory next) {
+        this(next, ChannelFactory.DEFAULT_EXECUTOR);
+    }
+    
+    /**
+     * @deprecated {@see #adapt(SyncChannelFactory, Executor)}
+     */
+    public SyncToAsyncChannelFactory(final SyncChannelFactory next, Executor executor) {
+        this.syncChannelFactory = next;
+        this.executor = executor;
+    }
+        
+    public AsyncChannel openAsyncChannel(URI location) throws IOException {
+        return SyncToAsyncChannel.adapt(syncChannelFactory.openSyncChannel(location),executor);
+    }
+
+    public AsyncChannelServer bindAsyncChannel(URI location) throws IOException {
+        return new SyncToAsyncChannelServer(syncChannelFactory.bindSyncChannel(location),executor);
+    }
+    
+    public SyncChannelFactory getSyncChannelFactory() {
+        return syncChannelFactory;
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelServer.java
index 54cae8c..8d6286a 100644
--- a/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/adapter/SyncToAsyncChannelServer.java
@@ -1,171 +1,171 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.adapter;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelFactory;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;

-import edu.emory.mathcs.backport.java.util.concurrent.Executor;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;

-

-/**

- * Adapts a {@see org.apache.activeio,SynchChannelServer} so that it provides an 

- * {@see org.apache.activeio.AsyncChannelServer} interface.  When this channel

- * is started, a background thread is used to poll the (@see org.apache.activeio.SynchChannelServer}

- * for accepted channel connections which are then delivered to the {@see org.apache.activeio.AcceptConsumer}.

- * 

- * @version $Revision$

- */

-final public class SyncToAsyncChannelServer implements AsyncChannelServer, Runnable {

-

-    private final SyncChannelServer syncChannelServer;

-    private final AtomicBoolean running = new AtomicBoolean(false);

-    private final Executor executor;

-    private AcceptListener acceptListener;

-    private CountDownLatch doneCountDownLatch;

-    

-    

-    static public AsyncChannelServer adapt(ChannelServer channel) {

-        return adapt(channel, ChannelFactory.DEFAULT_EXECUTOR);

-    }

-

-    static public AsyncChannelServer adapt(ChannelServer channel, Executor executor) {

-

-        // It might not need adapting

-        if( channel instanceof AsyncChannelServer ) {

-            return (AsyncChannelServer) channel;

-        }

-

-        // Can we just just undo the adaptor

-        if( channel.getClass() == SyncToAsyncChannel.class ) {

-            return ((AsyncToSyncChannelServer)channel).getAsyncChannelServer();

-        }

-        

-        return new SyncToAsyncChannelServer((SyncChannelServer)channel, executor);        

-    }

-    

-    public SyncToAsyncChannelServer(SyncChannelServer syncServer) {

-        this(syncServer, ChannelFactory.DEFAULT_EXECUTOR);

-    }

-    

-    public SyncToAsyncChannelServer(SyncChannelServer syncServer, Executor executor) {

-        this.syncChannelServer = syncServer;        

-        this.executor=executor;

-    }

-    

-    synchronized public void start() throws IOException {        

-        if (running.compareAndSet(false, true)) {

-            

-            if( acceptListener == null )

-                throw new IllegalStateException("AcceptListener must be set before object can be started.");

-

-            syncChannelServer.start();

-            

-            doneCountDownLatch = new CountDownLatch(1);

-            executor.execute(this);

-        }

-    }

-

-    synchronized public void stop() throws IOException {

-        if (running.compareAndSet(true, false)) {

-            try {

-                doneCountDownLatch.await(5, TimeUnit.SECONDS);

-            } catch (Throwable e) {

-            }

-            syncChannelServer.stop();

-        }

-    }

-

-    public void run() {

-        // Change the thread name.

-        String oldName = Thread.currentThread().getName();        

-        Thread.currentThread().setName( syncChannelServer.toString() );

-        try {

-	        while (running.get()) {

-	            try {

-	                Channel channel = syncChannelServer.accept(500);

-	                if( channel == null )

-	                    continue;                

-	                acceptListener.onAccept(channel);

-	            } catch (IOException e) {

-	                if( running.get() )

-	                    acceptListener.onAcceptError(e);        

-	        	} catch (Throwable e) {        	    

-	                if( running.get() )

-	                    acceptListener.onAcceptError((IOException)new IOException("Unexpected Error: "+e).initCause(e));

-	        	}

-	        }

-        } finally {

-            if( doneCountDownLatch!=null )

-                doneCountDownLatch.countDown();

-            Thread.currentThread().setName(oldName);            

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.AsyncChannelServer#setAcceptListener(org.apache.activeio.AcceptListener)

-     */

-    public void setAcceptListener(AcceptListener acceptListener) {

-        if(running.get()) 

-            throw new IllegalStateException("Cannot change the AcceptListener while the object is running.");        

-        this.acceptListener = acceptListener;

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        try {

-            stop();

-        } catch ( IOException ignore) {

-        }

-        syncChannelServer.dispose();

-    }

-

-    public URI getBindURI() {

-        return syncChannelServer.getBindURI();

-    }

-

-    public URI getConnectURI() {

-        return syncChannelServer.getConnectURI();

-    }

-

-    public SyncChannelServer getSynchChannelServer() {

-        return syncChannelServer;

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return syncChannelServer.getAdapter(target);

-    }    

-    

-    public String toString() {

-        return syncChannelServer.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.adapter;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelFactory;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
+import edu.emory.mathcs.backport.java.util.concurrent.Executor;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Adapts a {@see org.apache.activeio,SynchChannelServer} so that it provides an 
+ * {@see org.apache.activeio.AsyncChannelServer} interface.  When this channel
+ * is started, a background thread is used to poll the (@see org.apache.activeio.SynchChannelServer}
+ * for accepted channel connections which are then delivered to the {@see org.apache.activeio.AcceptConsumer}.
+ * 
+ * @version $Revision$
+ */
+final public class SyncToAsyncChannelServer implements AsyncChannelServer, Runnable {
+
+    private final SyncChannelServer syncChannelServer;
+    private final AtomicBoolean running = new AtomicBoolean(false);
+    private final Executor executor;
+    private AcceptListener acceptListener;
+    private CountDownLatch doneCountDownLatch;
+    
+    
+    static public AsyncChannelServer adapt(ChannelServer channel) {
+        return adapt(channel, ChannelFactory.DEFAULT_EXECUTOR);
+    }
+
+    static public AsyncChannelServer adapt(ChannelServer channel, Executor executor) {
+
+        // It might not need adapting
+        if( channel instanceof AsyncChannelServer ) {
+            return (AsyncChannelServer) channel;
+        }
+
+        // Can we just just undo the adaptor
+        if( channel.getClass() == SyncToAsyncChannel.class ) {
+            return ((AsyncToSyncChannelServer)channel).getAsyncChannelServer();
+        }
+        
+        return new SyncToAsyncChannelServer((SyncChannelServer)channel, executor);        
+    }
+    
+    public SyncToAsyncChannelServer(SyncChannelServer syncServer) {
+        this(syncServer, ChannelFactory.DEFAULT_EXECUTOR);
+    }
+    
+    public SyncToAsyncChannelServer(SyncChannelServer syncServer, Executor executor) {
+        this.syncChannelServer = syncServer;        
+        this.executor=executor;
+    }
+    
+    synchronized public void start() throws IOException {        
+        if (running.compareAndSet(false, true)) {
+            
+            if( acceptListener == null )
+                throw new IllegalStateException("AcceptListener must be set before object can be started.");
+
+            syncChannelServer.start();
+            
+            doneCountDownLatch = new CountDownLatch(1);
+            executor.execute(this);
+        }
+    }
+
+    synchronized public void stop() throws IOException {
+        if (running.compareAndSet(true, false)) {
+            try {
+                doneCountDownLatch.await(5, TimeUnit.SECONDS);
+            } catch (Throwable e) {
+            }
+            syncChannelServer.stop();
+        }
+    }
+
+    public void run() {
+        // Change the thread name.
+        String oldName = Thread.currentThread().getName();        
+        Thread.currentThread().setName( syncChannelServer.toString() );
+        try {
+	        while (running.get()) {
+	            try {
+	                Channel channel = syncChannelServer.accept(500);
+	                if( channel == null )
+	                    continue;                
+	                acceptListener.onAccept(channel);
+	            } catch (IOException e) {
+	                if( running.get() )
+	                    acceptListener.onAcceptError(e);        
+	        	} catch (Throwable e) {        	    
+	                if( running.get() )
+	                    acceptListener.onAcceptError((IOException)new IOException("Unexpected Error: "+e).initCause(e));
+	        	}
+	        }
+        } finally {
+            if( doneCountDownLatch!=null )
+                doneCountDownLatch.countDown();
+            Thread.currentThread().setName(oldName);            
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.AsyncChannelServer#setAcceptListener(org.apache.activeio.AcceptListener)
+     */
+    public void setAcceptListener(AcceptListener acceptListener) {
+        if(running.get()) 
+            throw new IllegalStateException("Cannot change the AcceptListener while the object is running.");        
+        this.acceptListener = acceptListener;
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        try {
+            stop();
+        } catch ( IOException ignore) {
+        }
+        syncChannelServer.dispose();
+    }
+
+    public URI getBindURI() {
+        return syncChannelServer.getBindURI();
+    }
+
+    public URI getConnectURI() {
+        return syncChannelServer.getConnectURI();
+    }
+
+    public SyncChannelServer getSynchChannelServer() {
+        return syncChannelServer;
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return syncChannelServer.getAdapter(target);
+    }    
+    
+    public String toString() {
+        return syncChannelServer.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/InvalidRecordLocationException.java b/activeio-core/src/main/java/org/apache/activeio/journal/InvalidRecordLocationException.java
index 3c8abe0..ce55ea7 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/InvalidRecordLocationException.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/InvalidRecordLocationException.java
@@ -1,59 +1,59 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal;

-

-/**

- * Exception thrown by a Journal to indicate that an invalid RecordLocation was detected.

- * 

- * @version $Revision: 1.1 $

- */

-public class InvalidRecordLocationException extends Exception {

-

-	/**

-     * Comment for <code>serialVersionUID</code>

-     */

-    private static final long serialVersionUID = 3618414947307239475L;

-

-    /**

-	 * 

-	 */

-	public InvalidRecordLocationException() {

-		super();

-	}

-

-	/**

-	 * @param msg

-	 */

-	public InvalidRecordLocationException(String msg) {

-		super(msg);

-	}

-

-	/**

-	 * @param msg

-	 * @param rootCause

-	 */

-	public InvalidRecordLocationException(String msg, Throwable rootCause) {

-		super(msg, rootCause);

-	}

-	

-	/**

-	 * @param rootCause

-	 */

-	public InvalidRecordLocationException(Throwable rootCause) {

-		super(rootCause);

-	}

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal;
+
+/**
+ * Exception thrown by a Journal to indicate that an invalid RecordLocation was detected.
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class InvalidRecordLocationException extends Exception {
+
+	/**
+     * Comment for <code>serialVersionUID</code>
+     */
+    private static final long serialVersionUID = 3618414947307239475L;
+
+    /**
+	 * 
+	 */
+	public InvalidRecordLocationException() {
+		super();
+	}
+
+	/**
+	 * @param msg
+	 */
+	public InvalidRecordLocationException(String msg) {
+		super(msg);
+	}
+
+	/**
+	 * @param msg
+	 * @param rootCause
+	 */
+	public InvalidRecordLocationException(String msg, Throwable rootCause) {
+		super(msg, rootCause);
+	}
+	
+	/**
+	 * @param rootCause
+	 */
+	public InvalidRecordLocationException(Throwable rootCause) {
+		super(rootCause);
+	}
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/Journal.java b/activeio-core/src/main/java/org/apache/activeio/journal/Journal.java
index 5f65649..faf7dbe 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/Journal.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/Journal.java
@@ -1,127 +1,127 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.Packet;

-

-/**

- * A Journal is a record logging Interface that can be used to implement 

- * a transaction log.  

- * 

- * 

- * This interface was largely extracted out of the HOWL project to allow 

- * ActiveMQ to switch between different Journal implementations verry easily. 

- * 

- * @version $Revision: 1.1 $

- */

-public interface Journal {

-

-	/**

-	 * Writes a {@see Packet} of  data to the journal.  If <code>sync</code>

-	 * is true, then this call blocks until the data has landed on the physical 

-	 * disk.  Otherwise, this enqueues the write request and returns.

-	 * 

-	 * @param record - the data to be written to disk.

-	 * @param sync - If this call should block until the data lands on disk.

-	 * 

-	 * @return RecordLocation the location where the data will be written to on disk.

-	 * 

-	 * @throws IOException if the write failed.

-	 * @throws IllegalStateException if the journal is closed.

-	 */

-	public RecordLocation write(Packet packet, boolean sync) throws IOException, IllegalStateException;

-

-	/**

-	 * Reads a previously written record from the journal. 

-	 *  

-	 * @param location is where to read the record from.

-	 * 

-	 * @return the data previously written at the <code>location</code>.

-	 * 

-	 * @throws InvalidRecordLocationException if <code>location</code> parameter is out of range.  

-	 *         It cannot be a location that is before the current mark. 

-	 * @throws IOException if the record could not be read.

-	 * @throws IllegalStateException if the journal is closed.

-	 */

-	public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException;

-

-	/**

-	 * Informs the journal that all the journal space up to the <code>location</code> is no longer

-	 * needed and can be reclaimed for reuse.

-	 * 

-	 * @param location the location of the record to mark.  All record locations before the marked 

-	 * location will no longger be vaild. 

-	 * 

-	 * @param sync if this call should block until the mark is set on the journal.

-	 * 

-	 * @throws InvalidRecordLocationException if <code>location</code> parameter is out of range.  

-	 *         It cannot be a location that is before the current mark. 

-	 * @throws IOException if the record could not be read.

-	 * @throws IllegalStateException if the journal is closed.

-	 */

-	public abstract void setMark(RecordLocation location, boolean sync)

-			throws InvalidRecordLocationException, IOException, IllegalStateException;

-	

-	/**

-	 * Obtains the mark that was set in the Journal.

-	 * 

-	 * @see read(RecordLocation location);

-	 * @return the mark that was set in the Journal.

-	 * @throws IllegalStateException if the journal is closed.

-	 */

-	public RecordLocation getMark() throws IllegalStateException;

-

-

-	/**

-	 * Close the Journal.  

-	 * This is blocking operation that waits for any pending put opperations to be forced to disk.

-	 * Once the Journal is closed, all other methods of the journal should throw IllegalStateException.

-	 * 

-	 * @throws IOException if an error occurs while the journal is being closed.

-	 */

-	public abstract void close() throws IOException;

-

-	/**

-	 * Allows you to get the next RecordLocation after the <code>location</code> that 

-	 * is in the journal.

-	 * 

-	 * @param location the reference location the is used to find the next location.

-	 * To get the oldest location available in the journal, <code>location</code> 

-	 * should be set to null.

-	 * 

-	 * 

-	 * @return the next record location

-	 * 

-	 * @throws InvalidRecordLocationException if <code>location</code> parameter is out of range.  

-	 *         It cannot be a location that is before the current mark. 

-	 * @throws IllegalStateException if the journal is closed.

-	 */

-	public abstract RecordLocation getNextRecordLocation(RecordLocation location)

-		throws InvalidRecordLocationException, IOException, IllegalStateException;

-

-

-	/**

-	 * Registers a <code>JournalEventListener</code> that will receive notifications from the Journal.

-	 * 

-	 * @param listener object that will receive journal events.

-	 * @throws IllegalStateException if the journal is closed.

-	 */

-	public abstract void setJournalEventListener(JournalEventListener listener) throws IllegalStateException;

-	

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.Packet;
+
+/**
+ * A Journal is a record logging Interface that can be used to implement 
+ * a transaction log.  
+ * 
+ * 
+ * This interface was largely extracted out of the HOWL project to allow 
+ * ActiveMQ to switch between different Journal implementations verry easily. 
+ * 
+ * @version $Revision: 1.1 $
+ */
+public interface Journal {
+
+	/**
+	 * Writes a {@see Packet} of  data to the journal.  If <code>sync</code>
+	 * is true, then this call blocks until the data has landed on the physical 
+	 * disk.  Otherwise, this enqueues the write request and returns.
+	 * 
+	 * @param record - the data to be written to disk.
+	 * @param sync - If this call should block until the data lands on disk.
+	 * 
+	 * @return RecordLocation the location where the data will be written to on disk.
+	 * 
+	 * @throws IOException if the write failed.
+	 * @throws IllegalStateException if the journal is closed.
+	 */
+	public RecordLocation write(Packet packet, boolean sync) throws IOException, IllegalStateException;
+
+	/**
+	 * Reads a previously written record from the journal. 
+	 *  
+	 * @param location is where to read the record from.
+	 * 
+	 * @return the data previously written at the <code>location</code>.
+	 * 
+	 * @throws InvalidRecordLocationException if <code>location</code> parameter is out of range.  
+	 *         It cannot be a location that is before the current mark. 
+	 * @throws IOException if the record could not be read.
+	 * @throws IllegalStateException if the journal is closed.
+	 */
+	public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException;
+
+	/**
+	 * Informs the journal that all the journal space up to the <code>location</code> is no longer
+	 * needed and can be reclaimed for reuse.
+	 * 
+	 * @param location the location of the record to mark.  All record locations before the marked 
+	 * location will no longger be vaild. 
+	 * 
+	 * @param sync if this call should block until the mark is set on the journal.
+	 * 
+	 * @throws InvalidRecordLocationException if <code>location</code> parameter is out of range.  
+	 *         It cannot be a location that is before the current mark. 
+	 * @throws IOException if the record could not be read.
+	 * @throws IllegalStateException if the journal is closed.
+	 */
+	public abstract void setMark(RecordLocation location, boolean sync)
+			throws InvalidRecordLocationException, IOException, IllegalStateException;
+	
+	/**
+	 * Obtains the mark that was set in the Journal.
+	 * 
+	 * @see read(RecordLocation location);
+	 * @return the mark that was set in the Journal.
+	 * @throws IllegalStateException if the journal is closed.
+	 */
+	public RecordLocation getMark() throws IllegalStateException;
+
+
+	/**
+	 * Close the Journal.  
+	 * This is blocking operation that waits for any pending put opperations to be forced to disk.
+	 * Once the Journal is closed, all other methods of the journal should throw IllegalStateException.
+	 * 
+	 * @throws IOException if an error occurs while the journal is being closed.
+	 */
+	public abstract void close() throws IOException;
+
+	/**
+	 * Allows you to get the next RecordLocation after the <code>location</code> that 
+	 * is in the journal.
+	 * 
+	 * @param location the reference location the is used to find the next location.
+	 * To get the oldest location available in the journal, <code>location</code> 
+	 * should be set to null.
+	 * 
+	 * 
+	 * @return the next record location
+	 * 
+	 * @throws InvalidRecordLocationException if <code>location</code> parameter is out of range.  
+	 *         It cannot be a location that is before the current mark. 
+	 * @throws IllegalStateException if the journal is closed.
+	 */
+	public abstract RecordLocation getNextRecordLocation(RecordLocation location)
+		throws InvalidRecordLocationException, IOException, IllegalStateException;
+
+
+	/**
+	 * Registers a <code>JournalEventListener</code> that will receive notifications from the Journal.
+	 * 
+	 * @param listener object that will receive journal events.
+	 * @throws IllegalStateException if the journal is closed.
+	 */
+	public abstract void setJournalEventListener(JournalEventListener listener) throws IllegalStateException;
+	
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/JournalEventListener.java b/activeio-core/src/main/java/org/apache/activeio/journal/JournalEventListener.java
index 475a904..8ff70ba 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/JournalEventListener.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/JournalEventListener.java
@@ -1,37 +1,37 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal;

-

-/**

- * Defines an object which listens for Journal Events.

- * 

- * @version $Revision: 1.1 $

- */

-public interface JournalEventListener {

-

-	/**

-	 * This event is issues when a Journal implementations wants to recover 

-	 * disk space used by old records.  If journal space is not reliquised 

-	 * by setting the Journal's mark at or past the <code>safeLocation</code>

-	 * further write opperations against the Journal may casuse IOExceptions 

-	 * to occur due to a log overflow condition.

-	 * 

-	 * @param safeLocation the oldest location that the journal recomends the mark to be set.

-	 */

-	void overflowNotification(RecordLocation safeLocation);

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal;
+
+/**
+ * Defines an object which listens for Journal Events.
+ * 
+ * @version $Revision: 1.1 $
+ */
+public interface JournalEventListener {
+
+	/**
+	 * This event is issues when a Journal implementations wants to recover 
+	 * disk space used by old records.  If journal space is not reliquised 
+	 * by setting the Journal's mark at or past the <code>safeLocation</code>
+	 * further write opperations against the Journal may casuse IOExceptions 
+	 * to occur due to a log overflow condition.
+	 * 
+	 * @param safeLocation the oldest location that the journal recomends the mark to be set.
+	 */
+	void overflowNotification(RecordLocation safeLocation);
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/RecordLocation.java b/activeio-core/src/main/java/org/apache/activeio/journal/RecordLocation.java
index bad482e..2bad2d8 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/RecordLocation.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/RecordLocation.java
@@ -1,30 +1,30 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal;

-

-/**

- * A RecordLocation is used to locate data records that have been 

- * logged to a Journal via the <code>Journal.put()</code> method call.

- * 

- * RecordLocation are comparable on the position in the Journal 

- * where they reside.

- * 

- * @version $Revision: 1.1 $

- */

-public interface RecordLocation extends Comparable {

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal;
+
+/**
+ * A RecordLocation is used to locate data records that have been 
+ * logged to a Journal via the <code>Journal.put()</code> method call.
+ * 
+ * RecordLocation are comparable on the position in the Journal 
+ * where they reside.
+ * 
+ * @version $Revision: 1.1 $
+ */
+public interface RecordLocation extends Comparable {
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/BatchedWrite.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/BatchedWrite.java
index 6edbd3b..aead517 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/BatchedWrite.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/BatchedWrite.java
@@ -1,142 +1,142 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import org.apache.activeio.packet.Packet;

-

-import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;

-

-/**

- * This contains all the data needed to write and force a list of records to a

- * LogFile. The more records that can be cramed into a single BatchedWrite, the

- * higher throughput that can be achived by a write and force operation.

- * 

- * @version $Revision: 1.1 $

- */

-final public class BatchedWrite {

-

-    private final Packet packet;

-    public Throwable error;

-    private Location mark;

-    private boolean appendDisabled = false;

-    private boolean appendInProgress = false;

-    private CountDownLatch writeDoneCountDownLatch;

-

-    /**

-     * @param packet

-     */

-    public BatchedWrite(Packet packet) {

-        this.packet = packet;

-    }

-

-    /**

-     * @throws InterruptedException

-     * 

-     */

-    synchronized private void disableAppend() throws InterruptedException {

-        appendDisabled = true;

-        while (appendInProgress) {

-            wait();

-        }

-    }

-

-    /**

-     * @param packet2

-     * @param mark2

-     * @return

-     */

-    public boolean append(Record record, Location recordMark, boolean force) {

-

-        synchronized (this) {

-            if (appendDisabled)

-                return false;

-            appendInProgress = true;

-        }

-        

-        

-        if( force && writeDoneCountDownLatch==null)

-            writeDoneCountDownLatch = new CountDownLatch(1);

-        

-        record.read(packet);

-

-        // if we fit the record in this batch

-        if ( !record.hasRemaining() ) {

-            if (recordMark != null)

-                mark = recordMark;

-        }

-

-        synchronized (this) {

-            appendInProgress = false;

-            this.notify();

-

-            if (appendDisabled)

-                return false;

-            else

-                return packet.remaining() > 0;

-        }

-    }

-

-    public void waitForForce() throws Throwable {

-        if( writeDoneCountDownLatch!=null ) {

-            writeDoneCountDownLatch.await();

-            synchronized (this) {

-                if (error != null)

-                    throw error;

-            }

-        }

-    }

-

-    public void forced() {

-        if( writeDoneCountDownLatch!=null ) {

-            writeDoneCountDownLatch.countDown();

-        }

-    }

-

-    public void writeFailed(Throwable error) {

-        if( writeDoneCountDownLatch!=null ) {

-            synchronized (this) {

-                this.error = error;

-            }

-            writeDoneCountDownLatch.countDown();

-        }

-    }

-

-    public Packet getPacket() {

-        return packet;

-    }

-

-    /**

-     * @return

-     */

-    public Location getMark() {

-        return mark;

-    }

-

-    /**

-     * @throws InterruptedException

-     * 

-     */

-    public void flip() throws InterruptedException {

-        disableAppend();

-        packet.flip();

-    }

-

-    public boolean getForce() {

-        return writeDoneCountDownLatch!=null;

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import org.apache.activeio.packet.Packet;
+
+import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
+
+/**
+ * This contains all the data needed to write and force a list of records to a
+ * LogFile. The more records that can be cramed into a single BatchedWrite, the
+ * higher throughput that can be achived by a write and force operation.
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class BatchedWrite {
+
+    private final Packet packet;
+    public Throwable error;
+    private Location mark;
+    private boolean appendDisabled = false;
+    private boolean appendInProgress = false;
+    private CountDownLatch writeDoneCountDownLatch;
+
+    /**
+     * @param packet
+     */
+    public BatchedWrite(Packet packet) {
+        this.packet = packet;
+    }
+
+    /**
+     * @throws InterruptedException
+     * 
+     */
+    synchronized private void disableAppend() throws InterruptedException {
+        appendDisabled = true;
+        while (appendInProgress) {
+            wait();
+        }
+    }
+
+    /**
+     * @param packet2
+     * @param mark2
+     * @return
+     */
+    public boolean append(Record record, Location recordMark, boolean force) {
+
+        synchronized (this) {
+            if (appendDisabled)
+                return false;
+            appendInProgress = true;
+        }
+        
+        
+        if( force && writeDoneCountDownLatch==null)
+            writeDoneCountDownLatch = new CountDownLatch(1);
+        
+        record.read(packet);
+
+        // if we fit the record in this batch
+        if ( !record.hasRemaining() ) {
+            if (recordMark != null)
+                mark = recordMark;
+        }
+
+        synchronized (this) {
+            appendInProgress = false;
+            this.notify();
+
+            if (appendDisabled)
+                return false;
+            else
+                return packet.remaining() > 0;
+        }
+    }
+
+    public void waitForForce() throws Throwable {
+        if( writeDoneCountDownLatch!=null ) {
+            writeDoneCountDownLatch.await();
+            synchronized (this) {
+                if (error != null)
+                    throw error;
+            }
+        }
+    }
+
+    public void forced() {
+        if( writeDoneCountDownLatch!=null ) {
+            writeDoneCountDownLatch.countDown();
+        }
+    }
+
+    public void writeFailed(Throwable error) {
+        if( writeDoneCountDownLatch!=null ) {
+            synchronized (this) {
+                this.error = error;
+            }
+            writeDoneCountDownLatch.countDown();
+        }
+    }
+
+    public Packet getPacket() {
+        return packet;
+    }
+
+    /**
+     * @return
+     */
+    public Location getMark() {
+        return mark;
+    }
+
+    /**
+     * @throws InterruptedException
+     * 
+     */
+    public void flip() throws InterruptedException {
+        disableAppend();
+        packet.flip();
+    }
+
+    public boolean getForce() {
+        return writeDoneCountDownLatch!=null;
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/ControlFile.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/ControlFile.java
index 4fb804a..3fc11b8 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/ControlFile.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/ControlFile.java
@@ -1,190 +1,190 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.File;

-import java.io.IOException;

-import java.io.RandomAccessFile;

-import java.nio.ByteBuffer;

-import java.nio.channels.FileChannel;

-import java.nio.channels.FileLock;

-import java.util.HashSet;

-import java.util.Properties;

-import java.util.Set;

-

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.Packet;

-

-/**

- * Control file holds the last known good state of the journal.  It stores the state in 

- * record that is versioned and repeated twice in the file so that a failure in the

- * middle of the write of the first or second record do not not result in an unknown

- * state. 

- * 

- * @version $Revision: 1.1 $

- */

-final public class ControlFile {

-

-    /** The File that holds the control data. */

-    private final RandomAccessFile file;

-    private final FileChannel channel;

-    private final ByteBufferPacket controlData;

-

-    private long controlDataVersion=0;

-    private FileLock lock;

-	private boolean disposed;

-    private static Set lockSet;

-    private String canonicalPath;

-

-    public ControlFile(File fileName, int controlDataSize) throws IOException {

-        canonicalPath = fileName.getCanonicalPath();

-        boolean existed = fileName.exists();        

-        file = new RandomAccessFile(fileName, "rw");

-        channel = file.getChannel();

-        controlData = new ByteBufferPacket(ByteBuffer.allocateDirect(controlDataSize));

-

-    }

-

-    /**

-     * Locks the control file.

-     * @throws IOException 

-     */

-    public void lock() throws IOException {

-        Set set = getVmLockSet();

-        synchronized (set) {

-            if (lock == null) {

-                if (!set.add(canonicalPath)) {

-                    throw new IOException("Journal is already opened by this application.");

-                }

-

-                lock = channel.tryLock();

-                if (lock == null) {

-                    set.remove(canonicalPath);

-                    throw new IOException("Journal is already opened by another application");

-                }

-            }

-        }

-    }

-

-    /**

-     * Un locks the control file.

-     * 

-     * @throws IOException

-     */

-    public void unlock() throws IOException {

-        Set set = getVmLockSet();

-        synchronized (set) {

-            if (lock != null) {

-                set.remove(canonicalPath);

-                lock.release();

-                lock = null;

-            }

-        }

-    }

-    

-    static private Set getVmLockSet() {

-        if ( lockSet == null ) { 

-            Properties properties = System.getProperties();

-            synchronized(properties) {

-                lockSet = (Set) properties.get("org.apache.activeio.journal.active.lockMap");

-                if( lockSet == null ) {

-                    lockSet = new HashSet();

-                }

-                properties.put("org.apache.activeio.journal.active.lockMap", lockSet);

-            }

-        }

-        return lockSet;

-    }

-

-    

-    public boolean load() throws IOException {

-        long l = file.length();

-        if( l < controlData.capacity() ) {

-            controlDataVersion=0;

-            controlData.position(0);

-            controlData.limit(0);

-            return false;

-        } else {            

-            file.seek(0);

-            long v1 = file.readLong();

-            file.seek(controlData.capacity()+8);

-            long v1check = file.readLong();

-            

-            file.seek(controlData.capacity()+16);

-            long v2 = file.readLong();

-            file.seek((controlData.capacity()*2)+24);

-            long v2check = file.readLong();

-            

-            if( v2 == v2check ) {

-                controlDataVersion = v2;

-                file.seek(controlData.capacity()+24);

-                controlData.clear();

-                channel.read(controlData.getByteBuffer());

-            } else if ( v1 == v1check ){

-                controlDataVersion = v1;

-                file.seek(controlData.capacity()+8);

-                controlData.clear();

-                channel.read(controlData.getByteBuffer());

-            } else {

-                // Bummer.. Both checks are screwed. we don't know

-                // if any of the two buffer are ok.  This should

-                // only happen is data got corrupted.

-                throw new IOException("Control data corrupted.");

-            }         

-            return true;

-        }

-    }

-    

-    public void store() throws IOException {

-        controlDataVersion++;

-        file.setLength((controlData.capacity()*2)+32);

-        file.seek(0);

-        

-        // Write the first copy of the control data.

-        file.writeLong(controlDataVersion);

-        controlData.clear();

-        channel.write(controlData.getByteBuffer());

-        file.writeLong(controlDataVersion);

-

-        // Write the second copy of the control data.

-        file.writeLong(controlDataVersion);

-        controlData.clear();

-        channel.write(controlData.getByteBuffer());

-        file.writeLong(controlDataVersion);

-        

-        channel.force(false);        

-    }

-

-    public Packet getControlData() {

-        controlData.clear();

-        return controlData;

-    }

-

-    public void dispose() {

-    	if( disposed )

-    		return;

-    	disposed=true;

-        try {

-            unlock();

-        } catch (IOException e) {

-        }

-        try {

-            file.close();

-        } catch (IOException e) {

-        }

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.Packet;
+
+/**
+ * Control file holds the last known good state of the journal.  It stores the state in 
+ * record that is versioned and repeated twice in the file so that a failure in the
+ * middle of the write of the first or second record do not not result in an unknown
+ * state. 
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class ControlFile {
+
+    /** The File that holds the control data. */
+    private final RandomAccessFile file;
+    private final FileChannel channel;
+    private final ByteBufferPacket controlData;
+
+    private long controlDataVersion=0;
+    private FileLock lock;
+	private boolean disposed;
+    private static Set lockSet;
+    private String canonicalPath;
+
+    public ControlFile(File fileName, int controlDataSize) throws IOException {
+        canonicalPath = fileName.getCanonicalPath();
+        boolean existed = fileName.exists();        
+        file = new RandomAccessFile(fileName, "rw");
+        channel = file.getChannel();
+        controlData = new ByteBufferPacket(ByteBuffer.allocateDirect(controlDataSize));
+
+    }
+
+    /**
+     * Locks the control file.
+     * @throws IOException 
+     */
+    public void lock() throws IOException {
+        Set set = getVmLockSet();
+        synchronized (set) {
+            if (lock == null) {
+                if (!set.add(canonicalPath)) {
+                    throw new IOException("Journal is already opened by this application.");
+                }
+
+                lock = channel.tryLock();
+                if (lock == null) {
+                    set.remove(canonicalPath);
+                    throw new IOException("Journal is already opened by another application");
+                }
+            }
+        }
+    }
+
+    /**
+     * Un locks the control file.
+     * 
+     * @throws IOException
+     */
+    public void unlock() throws IOException {
+        Set set = getVmLockSet();
+        synchronized (set) {
+            if (lock != null) {
+                set.remove(canonicalPath);
+                lock.release();
+                lock = null;
+            }
+        }
+    }
+    
+    static private Set getVmLockSet() {
+        if ( lockSet == null ) { 
+            Properties properties = System.getProperties();
+            synchronized(properties) {
+                lockSet = (Set) properties.get("org.apache.activeio.journal.active.lockMap");
+                if( lockSet == null ) {
+                    lockSet = new HashSet();
+                }
+                properties.put("org.apache.activeio.journal.active.lockMap", lockSet);
+            }
+        }
+        return lockSet;
+    }
+
+    
+    public boolean load() throws IOException {
+        long l = file.length();
+        if( l < controlData.capacity() ) {
+            controlDataVersion=0;
+            controlData.position(0);
+            controlData.limit(0);
+            return false;
+        } else {            
+            file.seek(0);
+            long v1 = file.readLong();
+            file.seek(controlData.capacity()+8);
+            long v1check = file.readLong();
+            
+            file.seek(controlData.capacity()+16);
+            long v2 = file.readLong();
+            file.seek((controlData.capacity()*2)+24);
+            long v2check = file.readLong();
+            
+            if( v2 == v2check ) {
+                controlDataVersion = v2;
+                file.seek(controlData.capacity()+24);
+                controlData.clear();
+                channel.read(controlData.getByteBuffer());
+            } else if ( v1 == v1check ){
+                controlDataVersion = v1;
+                file.seek(controlData.capacity()+8);
+                controlData.clear();
+                channel.read(controlData.getByteBuffer());
+            } else {
+                // Bummer.. Both checks are screwed. we don't know
+                // if any of the two buffer are ok.  This should
+                // only happen is data got corrupted.
+                throw new IOException("Control data corrupted.");
+            }         
+            return true;
+        }
+    }
+    
+    public void store() throws IOException {
+        controlDataVersion++;
+        file.setLength((controlData.capacity()*2)+32);
+        file.seek(0);
+        
+        // Write the first copy of the control data.
+        file.writeLong(controlDataVersion);
+        controlData.clear();
+        channel.write(controlData.getByteBuffer());
+        file.writeLong(controlDataVersion);
+
+        // Write the second copy of the control data.
+        file.writeLong(controlDataVersion);
+        controlData.clear();
+        channel.write(controlData.getByteBuffer());
+        file.writeLong(controlDataVersion);
+        
+        channel.force(false);        
+    }
+
+    public Packet getControlData() {
+        controlData.clear();
+        return controlData;
+    }
+
+    public void dispose() {
+    	if( disposed )
+    		return;
+    	disposed=true;
+        try {
+            unlock();
+        } catch (IOException e) {
+        }
+        try {
+            file.close();
+        } catch (IOException e) {
+        }
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/JournalImpl.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/JournalImpl.java
index 76dee8b..29522b1 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/JournalImpl.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/JournalImpl.java
@@ -1,461 +1,461 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.File;

-import java.io.IOException;

-import java.io.InterruptedIOException;

-

-import org.apache.activeio.journal.InvalidRecordLocationException;

-import org.apache.activeio.journal.Journal;

-import org.apache.activeio.journal.JournalEventListener;

-import org.apache.activeio.journal.RecordLocation;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.ByteBufferPacketPool;

-import org.apache.activeio.packet.Packet;

-

-import edu.emory.mathcs.backport.java.util.concurrent.Callable;

-import edu.emory.mathcs.backport.java.util.concurrent.ExecutionException;

-import edu.emory.mathcs.backport.java.util.concurrent.FutureTask;

-import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;

-import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- * A high speed Journal implementation. Inspired by the ideas of the <a

- * href="http://howl.objectweb.org/">Howl </a> project but tailored to the needs

- * of ActiveMQ. <p/>This Journal provides the following features:

- * <ul>

- * <li>Concurrent writes are batched into a single write/force done by a

- * background thread.</li>

- * <li>Uses preallocated logs to avoid disk fragmentation and performance

- * degregation.</li>

- * <li>The number and size of the preallocated logs are configurable.</li>

- * <li>Uses direct ByteBuffers to write data to log files.</li>

- * <li>Allows logs to grow in case of an overflow condition so that overflow

- * exceptions are not not thrown. Grown logs that are inactivate (due to a new

- * mark) are resized to their original size.</li>

- * <li>No limit on the size of the record written to the journal</li>

- * <li>Should be possible to extend so that multiple physical disk are used

- * concurrently to increase throughput and decrease latency.</li>

- * </ul>

- * <p/>

- * 

- * @version $Revision: 1.1 $

- */

-final public class JournalImpl implements Journal {

-

-    public static final int DEFAULT_POOL_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPoolSize", ""+(5)));

-    public static final int DEFAULT_PACKET_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPacketSize", ""+(1024*1024*4)));

-

-    static final private int OVERFLOW_RENOTIFICATION_DELAY = 500;

-    

-    static private ByteBufferPacketPool lastPool;

-    

-    private boolean disposed = false;

-

-    // The id of the current log file that is being filled.

-    private int appendLogFileId = 0;

-

-    // The offset in the current log file that is being filled.

-    private int appendLogFileOffset = 0;

-

-    // Used to batch writes together.

-    private BatchedWrite pendingBatchWrite;

-    

-    private Location lastMarkedLocation;

-    private LogFileManager file;

-    private ThreadPoolExecutor executor;

-    private int rolloverFence;

-    private JournalEventListener eventListener;

-    private ByteBufferPacketPool packetPool;

-    private long overflowNotificationTime = System.currentTimeMillis();

-    private Packet markPacket = new ByteArrayPacket(new byte[Location.SERIALIZED_SIZE]);

-

-    public JournalImpl(File logDirectory) throws IOException {

-        this(new LogFileManager(logDirectory));

-    }

-

-    public JournalImpl(File logDirectory, int logFileCount, int logFileSize) throws IOException {

-        this(new LogFileManager(logDirectory, logFileCount, logFileSize, null));

-    }

-    

-    public JournalImpl(File logDirectory, int logFileCount, int logFileSize, File archiveDirectory) throws IOException {

-        this(new LogFileManager(logDirectory, logFileCount, logFileSize, archiveDirectory));

-    }

-

-    public JournalImpl(LogFileManager logFile) {

-        this.file = logFile;

-        this.packetPool = createBufferPool();

-        this.executor = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue(), new ThreadFactory() {

-            public Thread newThread(Runnable runnable) {

-                Thread answer = new Thread(runnable, "Journal Writer");

-                answer.setPriority(Thread.MAX_PRIORITY);

-                answer.setDaemon(true);

-                return answer;

-            }

-        });

-        executor.allowCoreThreadTimeOut(true);

-        

-        lastMarkedLocation = file.getLastMarkedRecordLocation();

-        Location nextAppendLocation = file.getNextAppendLocation();

-        appendLogFileId = nextAppendLocation.getLogFileId();

-        appendLogFileOffset = nextAppendLocation.getLogFileOffset();

-        

-        rolloverFence = (file.getInitialLogFileSize() / 10) * 9;

-    }

-

-    

-    /**

-     * When running unit tests we may not be able to create new pools fast enough

-     * since the old pools are not being gc'ed fast enough.  So we pool the pool.

-     * @return

-     */

-    synchronized static private ByteBufferPacketPool createBufferPool() {

-        if( lastPool !=null ) {

-            ByteBufferPacketPool rc = lastPool;

-            lastPool = null;

-            return rc;

-        } else { 

-            return new ByteBufferPacketPool(DEFAULT_POOL_SIZE, DEFAULT_PACKET_SIZE);

-        }

-    }

-    

-    /**

-     * When running unit tests we may not be able to create new pools fast enough

-     * since the old pools are not being gc'ed fast enough.  So we pool the pool.

-     * @return

-     */

-    synchronized static private void disposeBufferPool(ByteBufferPacketPool pool) {

-        if( lastPool!=null ) {

-            pool.dispose();

-        } else {

-            pool.waitForPacketsToReturn();

-            lastPool = pool;

-        }

-    }

-

-

-

-    public RecordLocation write(Packet data, boolean sync) throws IOException {

-        return write(LogFileManager.DATA_RECORD_TYPE, data, sync, null);

-    }

-

-    private Location write(byte recordType, Packet data, boolean sync, Location mark) throws IOException {

-        try {

-            Location location;

-            BatchedWrite writeCommand;

-            

-            Record record = new Record(recordType, data, mark);

-            

-            // The following synchronized block is the bottle neck of the journal.  Make this

-            // code faster and the journal should speed up.

-            synchronized (this) {

-                if (disposed) {

-                    throw new IOException("Journal has been closed.");

-                }

-

-                // Create our record

-                location = new Location(appendLogFileId, appendLogFileOffset);

-                record.setLocation(location);

-                

-                // Piggy back the packet on the pending write batch.

-                writeCommand = addToPendingWriteBatch(record, mark, sync);

-

-                // Update where the next record will land.

-                appendLogFileOffset += data.limit() + Record.RECORD_BASE_SIZE;

-                rolloverCheck();

-            }

-

-            if (sync) {

-                writeCommand.waitForForce();

-            }

-

-            return location;

-        } catch (IOException e) {

-            throw e;

-        } catch (InterruptedException e) {

-            throw (IOException) new InterruptedIOException().initCause(e);

-        } catch (Throwable e) {

-            throw (IOException) new IOException("Write failed: " + e).initCause(e);

-        }

-    }

-

-    /**

-     * @param record

-     * @return

-     * @throws InterruptedException

-     */

-    private BatchedWrite addToPendingWriteBatch(Record record, Location mark, boolean force) throws InterruptedException {

-

-        // Load the write batch up with data from our record.

-        // it may take more than one write batch if the record is large.

-        BatchedWrite answer = null;

-        while (record.hasRemaining()) {

-            

-            // Do we need another BatchWrite?

-            boolean queueTheWrite=false;

-            if (pendingBatchWrite == null) {

-                pendingBatchWrite =  new BatchedWrite(packetPool.getPacket());

-                queueTheWrite = true;

-            }

-            answer = pendingBatchWrite;

-

-            // Can we continue to use the pendingBatchWrite?

-            boolean full = !pendingBatchWrite.append(record, mark, force);

-            

-            if( queueTheWrite ) {

-                final BatchedWrite queuedWrite = pendingBatchWrite;

-                executor.execute(new Runnable() {

-                    public void run() {

-                        try {

-                            queuedWrite(queuedWrite);

-                        } catch (InterruptedException e) {

-                        }

-                    }

-                });

-            }

-            

-            if( full )

-                pendingBatchWrite = null;            

-        }

-        return answer;

-

-    }

-

-    /**

-     * This is a blocking call

-     * 

-     * @param write

-     * @throws InterruptedException

-     */

-    private void queuedWrite(BatchedWrite write) throws InterruptedException {

-

-        // Stop other threads from appending more pendingBatchWrite.

-        write.flip();

-

-        // Do the write.

-        try {

-            file.append(write);

-            write.forced();

-        } catch (Throwable e) {

-            write.writeFailed(e);

-        } finally {

-            write.getPacket().dispose();

-        }

-    }

-

-    /**

-     * 

-     */

-    private void rolloverCheck() throws IOException {

-

-        // See if we need to issue an overflow notification.

-        if (eventListener != null && file.isPastHalfActive()

-                && overflowNotificationTime + OVERFLOW_RENOTIFICATION_DELAY < System.currentTimeMillis()) {

-

-            // We need to send an overflow notification to free up

-            // some logFiles.

-            Location safeSpot = file.getFirstRecordLocationOfSecondActiveLogFile();

-            eventListener.overflowNotification(safeSpot);

-            overflowNotificationTime = System.currentTimeMillis();

-        }

-

-        // Is it time to roll over?

-        if (appendLogFileOffset > rolloverFence ) {

-

-            // Can we roll over?

-            if ( !file.canActivateNextLogFile() ) {

-                // don't delay the next overflow notification.

-                overflowNotificationTime -= OVERFLOW_RENOTIFICATION_DELAY;

-                

-            } else {

-                

-                try {

-                    final FutureTask result = new FutureTask(new Callable() {

-                        public Object call() throws Exception {

-                            return queuedActivateNextLogFile();

-                        }});

-                    executor.execute(result);

-                    Location location = (Location) result.get();

-                    appendLogFileId = location.getLogFileId();

-                    appendLogFileOffset = location.getLogFileOffset();

-    

-                } catch (InterruptedException e) {

-                    throw (IOException) new IOException("Interrupted.").initCause(e);

-                }

-                catch (ExecutionException e) {

-                    throw handleExecutionException(e);

-                }

-            }

-        }

-    }

-

-    /**

-     * This is a blocking call

-     */

-    private Location queuedActivateNextLogFile() throws IOException {

-        file.activateNextLogFile();

-        return file.getNextAppendLocation();

-    }

-

-    

-    

-    /**

-     * @param recordLocator

-     * @param force

-     * @return

-     * @throws InvalidRecordLocationException

-     * @throws IOException

-     * @throws InterruptedException

-     */

-    synchronized public void setMark(RecordLocation l, boolean force) throws InvalidRecordLocationException,

-            IOException {

-        

-        Location location = (Location) l;

-        if (location == null)

-            throw new InvalidRecordLocationException("The location cannot be null.");

-        if (lastMarkedLocation != null && location.compareTo(lastMarkedLocation) < 0)

-            throw new InvalidRecordLocationException("The location is less than the last mark.");

-        

-        markPacket.clear();

-        location.writeToPacket(markPacket);    

-        markPacket.flip();

-        write(LogFileManager.MARK_RECORD_TYPE, markPacket, force, location);

-        

-        lastMarkedLocation = location;

-    }

-

-    /**

-     * @return

-     */

-    public RecordLocation getMark() {

-        return lastMarkedLocation;

-    }

-

-    /**

-     * @param lastLocation

-     * @return

-     * @throws IOException

-     * @throws InvalidRecordLocationException

-     */

-    public RecordLocation getNextRecordLocation(final RecordLocation lastLocation) throws IOException,

-            InvalidRecordLocationException {

-        

-        if (lastLocation == null) {

-            if (lastMarkedLocation != null) {

-                return lastMarkedLocation;

-            } else {

-                return file.getFirstActiveLogLocation();

-            }

-        }

-

-        // Run this in the queued executor thread.

-        try {

-            final FutureTask result = new FutureTask(new Callable() {

-                public Object call() throws Exception {

-                    return queuedGetNextRecordLocation((Location) lastLocation);

-                }});

-            executor.execute(result);

-            return (Location) result.get();

-        } catch (InterruptedException e) {

-            throw (IOException) new IOException("Interrupted.").initCause(e);

-        }

-        catch (ExecutionException e) {

-            throw handleExecutionException(e);

-        }

-    }

-

-    protected IOException handleExecutionException(ExecutionException e) throws IOException {

-        Throwable cause = e.getCause();

-        if (cause instanceof IOException) {

-            return (IOException) cause;

-        }

-        else {

-            return (IOException) new IOException(cause.getMessage()).initCause(cause);

-        }

-    }

-

-    private Location queuedGetNextRecordLocation(Location location) throws IOException, InvalidRecordLocationException {

-        return file.getNextDataRecordLocation(location);

-    }

-

-    /**

-     * @param location

-     * @return

-     * @throws InvalidRecordLocationException

-     * @throws IOException

-     */

-    public Packet read(final RecordLocation l) throws IOException, InvalidRecordLocationException {

-        final Location location = (Location) l;

-        // Run this in the queued executor thread.

-        try {

-            final FutureTask result = new FutureTask(new Callable() {

-                public Object call() throws Exception {

-                    return file.readPacket(location);

-                }});

-            executor.execute(result);

-            return (Packet) result.get();

-        } catch (InterruptedException e) {

-            throw (IOException) new IOException("Interrupted.").initCause(e);

-        }

-        catch (ExecutionException e) {

-            throw handleExecutionException(e);

-        }

-    }

-

-    public void setJournalEventListener(JournalEventListener eventListener) {

-        this.eventListener = eventListener;

-    }

-

-    /**

-     * @deprecated @see #dispose()

-     */

-    public void close() throws IOException {

-    	dispose();

-    }

-    

-    /**

-     */

-    public void dispose() {

-        if (disposed)

-            return;

-        disposed=true;

-        executor.shutdown();

-        file.dispose();

-        ByteBufferPacketPool pool = packetPool;

-        packetPool=null;

-        disposeBufferPool(pool);

-    }

-

-    /**

-     * @return

-     */

-    public File getLogDirectory() {

-        return file.getLogDirectory();

-    }

-

-    public int getInitialLogFileSize() {

-        return file.getInitialLogFileSize();

-    }

-    

-    public String toString() {

-        return "Active Journal: using "+file.getOnlineLogFileCount()+" x " + (file.getInitialLogFileSize()/(1024*1024f)) + " Megs at: " + getLogDirectory();

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InterruptedIOException;
+
+import org.apache.activeio.journal.InvalidRecordLocationException;
+import org.apache.activeio.journal.Journal;
+import org.apache.activeio.journal.JournalEventListener;
+import org.apache.activeio.journal.RecordLocation;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.ByteBufferPacketPool;
+import org.apache.activeio.packet.Packet;
+
+import edu.emory.mathcs.backport.java.util.concurrent.Callable;
+import edu.emory.mathcs.backport.java.util.concurrent.ExecutionException;
+import edu.emory.mathcs.backport.java.util.concurrent.FutureTask;
+import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;
+import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ * A high speed Journal implementation. Inspired by the ideas of the <a
+ * href="http://howl.objectweb.org/">Howl </a> project but tailored to the needs
+ * of ActiveMQ. <p/>This Journal provides the following features:
+ * <ul>
+ * <li>Concurrent writes are batched into a single write/force done by a
+ * background thread.</li>
+ * <li>Uses preallocated logs to avoid disk fragmentation and performance
+ * degregation.</li>
+ * <li>The number and size of the preallocated logs are configurable.</li>
+ * <li>Uses direct ByteBuffers to write data to log files.</li>
+ * <li>Allows logs to grow in case of an overflow condition so that overflow
+ * exceptions are not not thrown. Grown logs that are inactivate (due to a new
+ * mark) are resized to their original size.</li>
+ * <li>No limit on the size of the record written to the journal</li>
+ * <li>Should be possible to extend so that multiple physical disk are used
+ * concurrently to increase throughput and decrease latency.</li>
+ * </ul>
+ * <p/>
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class JournalImpl implements Journal {
+
+    public static final int DEFAULT_POOL_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPoolSize", ""+(5)));
+    public static final int DEFAULT_PACKET_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPacketSize", ""+(1024*1024*4)));
+
+    static final private int OVERFLOW_RENOTIFICATION_DELAY = 500;
+    
+    static private ByteBufferPacketPool lastPool;
+    
+    private boolean disposed = false;
+
+    // The id of the current log file that is being filled.
+    private int appendLogFileId = 0;
+
+    // The offset in the current log file that is being filled.
+    private int appendLogFileOffset = 0;
+
+    // Used to batch writes together.
+    private BatchedWrite pendingBatchWrite;
+    
+    private Location lastMarkedLocation;
+    private LogFileManager file;
+    private ThreadPoolExecutor executor;
+    private int rolloverFence;
+    private JournalEventListener eventListener;
+    private ByteBufferPacketPool packetPool;
+    private long overflowNotificationTime = System.currentTimeMillis();
+    private Packet markPacket = new ByteArrayPacket(new byte[Location.SERIALIZED_SIZE]);
+
+    public JournalImpl(File logDirectory) throws IOException {
+        this(new LogFileManager(logDirectory));
+    }
+
+    public JournalImpl(File logDirectory, int logFileCount, int logFileSize) throws IOException {
+        this(new LogFileManager(logDirectory, logFileCount, logFileSize, null));
+    }
+    
+    public JournalImpl(File logDirectory, int logFileCount, int logFileSize, File archiveDirectory) throws IOException {
+        this(new LogFileManager(logDirectory, logFileCount, logFileSize, archiveDirectory));
+    }
+
+    public JournalImpl(LogFileManager logFile) {
+        this.file = logFile;
+        this.packetPool = createBufferPool();
+        this.executor = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue(), new ThreadFactory() {
+            public Thread newThread(Runnable runnable) {
+                Thread answer = new Thread(runnable, "Journal Writer");
+                answer.setPriority(Thread.MAX_PRIORITY);
+                answer.setDaemon(true);
+                return answer;
+            }
+        });
+        executor.allowCoreThreadTimeOut(true);
+        
+        lastMarkedLocation = file.getLastMarkedRecordLocation();
+        Location nextAppendLocation = file.getNextAppendLocation();
+        appendLogFileId = nextAppendLocation.getLogFileId();
+        appendLogFileOffset = nextAppendLocation.getLogFileOffset();
+        
+        rolloverFence = (file.getInitialLogFileSize() / 10) * 9;
+    }
+
+    
+    /**
+     * When running unit tests we may not be able to create new pools fast enough
+     * since the old pools are not being gc'ed fast enough.  So we pool the pool.
+     * @return
+     */
+    synchronized static private ByteBufferPacketPool createBufferPool() {
+        if( lastPool !=null ) {
+            ByteBufferPacketPool rc = lastPool;
+            lastPool = null;
+            return rc;
+        } else { 
+            return new ByteBufferPacketPool(DEFAULT_POOL_SIZE, DEFAULT_PACKET_SIZE);
+        }
+    }
+    
+    /**
+     * When running unit tests we may not be able to create new pools fast enough
+     * since the old pools are not being gc'ed fast enough.  So we pool the pool.
+     * @return
+     */
+    synchronized static private void disposeBufferPool(ByteBufferPacketPool pool) {
+        if( lastPool!=null ) {
+            pool.dispose();
+        } else {
+            pool.waitForPacketsToReturn();
+            lastPool = pool;
+        }
+    }
+
+
+
+    public RecordLocation write(Packet data, boolean sync) throws IOException {
+        return write(LogFileManager.DATA_RECORD_TYPE, data, sync, null);
+    }
+
+    private Location write(byte recordType, Packet data, boolean sync, Location mark) throws IOException {
+        try {
+            Location location;
+            BatchedWrite writeCommand;
+            
+            Record record = new Record(recordType, data, mark);
+            
+            // The following synchronized block is the bottle neck of the journal.  Make this
+            // code faster and the journal should speed up.
+            synchronized (this) {
+                if (disposed) {
+                    throw new IOException("Journal has been closed.");
+                }
+
+                // Create our record
+                location = new Location(appendLogFileId, appendLogFileOffset);
+                record.setLocation(location);
+                
+                // Piggy back the packet on the pending write batch.
+                writeCommand = addToPendingWriteBatch(record, mark, sync);
+
+                // Update where the next record will land.
+                appendLogFileOffset += data.limit() + Record.RECORD_BASE_SIZE;
+                rolloverCheck();
+            }
+
+            if (sync) {
+                writeCommand.waitForForce();
+            }
+
+            return location;
+        } catch (IOException e) {
+            throw e;
+        } catch (InterruptedException e) {
+            throw (IOException) new InterruptedIOException().initCause(e);
+        } catch (Throwable e) {
+            throw (IOException) new IOException("Write failed: " + e).initCause(e);
+        }
+    }
+
+    /**
+     * @param record
+     * @return
+     * @throws InterruptedException
+     */
+    private BatchedWrite addToPendingWriteBatch(Record record, Location mark, boolean force) throws InterruptedException {
+
+        // Load the write batch up with data from our record.
+        // it may take more than one write batch if the record is large.
+        BatchedWrite answer = null;
+        while (record.hasRemaining()) {
+            
+            // Do we need another BatchWrite?
+            boolean queueTheWrite=false;
+            if (pendingBatchWrite == null) {
+                pendingBatchWrite =  new BatchedWrite(packetPool.getPacket());
+                queueTheWrite = true;
+            }
+            answer = pendingBatchWrite;
+
+            // Can we continue to use the pendingBatchWrite?
+            boolean full = !pendingBatchWrite.append(record, mark, force);
+            
+            if( queueTheWrite ) {
+                final BatchedWrite queuedWrite = pendingBatchWrite;
+                executor.execute(new Runnable() {
+                    public void run() {
+                        try {
+                            queuedWrite(queuedWrite);
+                        } catch (InterruptedException e) {
+                        }
+                    }
+                });
+            }
+            
+            if( full )
+                pendingBatchWrite = null;            
+        }
+        return answer;
+
+    }
+
+    /**
+     * This is a blocking call
+     * 
+     * @param write
+     * @throws InterruptedException
+     */
+    private void queuedWrite(BatchedWrite write) throws InterruptedException {
+
+        // Stop other threads from appending more pendingBatchWrite.
+        write.flip();
+
+        // Do the write.
+        try {
+            file.append(write);
+            write.forced();
+        } catch (Throwable e) {
+            write.writeFailed(e);
+        } finally {
+            write.getPacket().dispose();
+        }
+    }
+
+    /**
+     * 
+     */
+    private void rolloverCheck() throws IOException {
+
+        // See if we need to issue an overflow notification.
+        if (eventListener != null && file.isPastHalfActive()
+                && overflowNotificationTime + OVERFLOW_RENOTIFICATION_DELAY < System.currentTimeMillis()) {
+
+            // We need to send an overflow notification to free up
+            // some logFiles.
+            Location safeSpot = file.getFirstRecordLocationOfSecondActiveLogFile();
+            eventListener.overflowNotification(safeSpot);
+            overflowNotificationTime = System.currentTimeMillis();
+        }
+
+        // Is it time to roll over?
+        if (appendLogFileOffset > rolloverFence ) {
+
+            // Can we roll over?
+            if ( !file.canActivateNextLogFile() ) {
+                // don't delay the next overflow notification.
+                overflowNotificationTime -= OVERFLOW_RENOTIFICATION_DELAY;
+                
+            } else {
+                
+                try {
+                    final FutureTask result = new FutureTask(new Callable() {
+                        public Object call() throws Exception {
+                            return queuedActivateNextLogFile();
+                        }});
+                    executor.execute(result);
+                    Location location = (Location) result.get();
+                    appendLogFileId = location.getLogFileId();
+                    appendLogFileOffset = location.getLogFileOffset();
+    
+                } catch (InterruptedException e) {
+                    throw (IOException) new IOException("Interrupted.").initCause(e);
+                }
+                catch (ExecutionException e) {
+                    throw handleExecutionException(e);
+                }
+            }
+        }
+    }
+
+    /**
+     * This is a blocking call
+     */
+    private Location queuedActivateNextLogFile() throws IOException {
+        file.activateNextLogFile();
+        return file.getNextAppendLocation();
+    }
+
+    
+    
+    /**
+     * @param recordLocator
+     * @param force
+     * @return
+     * @throws InvalidRecordLocationException
+     * @throws IOException
+     * @throws InterruptedException
+     */
+    synchronized public void setMark(RecordLocation l, boolean force) throws InvalidRecordLocationException,
+            IOException {
+        
+        Location location = (Location) l;
+        if (location == null)
+            throw new InvalidRecordLocationException("The location cannot be null.");
+        if (lastMarkedLocation != null && location.compareTo(lastMarkedLocation) < 0)
+            throw new InvalidRecordLocationException("The location is less than the last mark.");
+        
+        markPacket.clear();
+        location.writeToPacket(markPacket);    
+        markPacket.flip();
+        write(LogFileManager.MARK_RECORD_TYPE, markPacket, force, location);
+        
+        lastMarkedLocation = location;
+    }
+
+    /**
+     * @return
+     */
+    public RecordLocation getMark() {
+        return lastMarkedLocation;
+    }
+
+    /**
+     * @param lastLocation
+     * @return
+     * @throws IOException
+     * @throws InvalidRecordLocationException
+     */
+    public RecordLocation getNextRecordLocation(final RecordLocation lastLocation) throws IOException,
+            InvalidRecordLocationException {
+        
+        if (lastLocation == null) {
+            if (lastMarkedLocation != null) {
+                return lastMarkedLocation;
+            } else {
+                return file.getFirstActiveLogLocation();
+            }
+        }
+
+        // Run this in the queued executor thread.
+        try {
+            final FutureTask result = new FutureTask(new Callable() {
+                public Object call() throws Exception {
+                    return queuedGetNextRecordLocation((Location) lastLocation);
+                }});
+            executor.execute(result);
+            return (Location) result.get();
+        } catch (InterruptedException e) {
+            throw (IOException) new IOException("Interrupted.").initCause(e);
+        }
+        catch (ExecutionException e) {
+            throw handleExecutionException(e);
+        }
+    }
+
+    protected IOException handleExecutionException(ExecutionException e) throws IOException {
+        Throwable cause = e.getCause();
+        if (cause instanceof IOException) {
+            return (IOException) cause;
+        }
+        else {
+            return (IOException) new IOException(cause.getMessage()).initCause(cause);
+        }
+    }
+
+    private Location queuedGetNextRecordLocation(Location location) throws IOException, InvalidRecordLocationException {
+        return file.getNextDataRecordLocation(location);
+    }
+
+    /**
+     * @param location
+     * @return
+     * @throws InvalidRecordLocationException
+     * @throws IOException
+     */
+    public Packet read(final RecordLocation l) throws IOException, InvalidRecordLocationException {
+        final Location location = (Location) l;
+        // Run this in the queued executor thread.
+        try {
+            final FutureTask result = new FutureTask(new Callable() {
+                public Object call() throws Exception {
+                    return file.readPacket(location);
+                }});
+            executor.execute(result);
+            return (Packet) result.get();
+        } catch (InterruptedException e) {
+            throw (IOException) new IOException("Interrupted.").initCause(e);
+        }
+        catch (ExecutionException e) {
+            throw handleExecutionException(e);
+        }
+    }
+
+    public void setJournalEventListener(JournalEventListener eventListener) {
+        this.eventListener = eventListener;
+    }
+
+    /**
+     * @deprecated @see #dispose()
+     */
+    public void close() throws IOException {
+    	dispose();
+    }
+    
+    /**
+     */
+    public void dispose() {
+        if (disposed)
+            return;
+        disposed=true;
+        executor.shutdown();
+        file.dispose();
+        ByteBufferPacketPool pool = packetPool;
+        packetPool=null;
+        disposeBufferPool(pool);
+    }
+
+    /**
+     * @return
+     */
+    public File getLogDirectory() {
+        return file.getLogDirectory();
+    }
+
+    public int getInitialLogFileSize() {
+        return file.getInitialLogFileSize();
+    }
+    
+    public String toString() {
+        return "Active Journal: using "+file.getOnlineLogFileCount()+" x " + (file.getInitialLogFileSize()/(1024*1024f)) + " Megs at: " + getLogDirectory();
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/Location.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/Location.java
index 8de750e..21a6a88 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/Location.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/Location.java
@@ -1,96 +1,96 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.DataInput;

-import java.io.DataOutput;

-import java.io.IOException;

-

-import org.apache.activeio.journal.RecordLocation;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.PacketData;

-

-/**

- * Defines a where a record can be located in the Journal.

- * 

- * @version $Revision: 1.1 $

- */

-final public class Location implements RecordLocation {

-    

-    static final public int SERIALIZED_SIZE=8;

-

-    final private int logFileId;

-    final private int logFileOffset;

-

-    public Location(int logFileId, int fileOffset) {

-        this.logFileId = logFileId;

-        this.logFileOffset = fileOffset;

-    }

-

-    public int compareTo(Object o) {

-        int rc = logFileId - ((Location) o).logFileId;

-        if (rc != 0)

-            return rc;

-

-        return logFileOffset - ((Location) o).logFileOffset;

-    }

-

-    public int hashCode() {

-        return logFileOffset ^ logFileId;

-    }

-

-    public boolean equals(Object o) {

-        if (o == null || o.getClass() != Location.class)

-            return false;

-        Location rl = (Location) o;

-        return rl.logFileId == this.logFileId && rl.logFileOffset == this.logFileOffset;

-    }

-

-    public String toString() {

-        return "" + logFileId + ":" + logFileOffset;

-    }

-

-    public int getLogFileId() {

-        return logFileId;

-    }

-

-    public int getLogFileOffset() {

-        return logFileOffset;

-    }

-    

-    public void writeToPacket(Packet packet) throws IOException {

-        PacketData data = new PacketData(packet);

-        data.writeInt(logFileId);

-        data.writeInt(logFileOffset);

-    }

-

-    public void writeToDataOutput(DataOutput data) throws IOException {

-        data.writeInt(logFileId);

-        data.writeInt(logFileOffset);

-    }    

-

-    static public Location readFromPacket(Packet packet) throws IOException {

-        PacketData data = new PacketData(packet);

-        return new Location(data.readInt(), data.readInt());

-    }

-

-    public static Location readFromDataInput(DataInput data) throws IOException {

-        return new Location(data.readInt(), data.readInt());

-    }

-

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+import org.apache.activeio.journal.RecordLocation;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.PacketData;
+
+/**
+ * Defines a where a record can be located in the Journal.
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class Location implements RecordLocation {
+    
+    static final public int SERIALIZED_SIZE=8;
+
+    final private int logFileId;
+    final private int logFileOffset;
+
+    public Location(int logFileId, int fileOffset) {
+        this.logFileId = logFileId;
+        this.logFileOffset = fileOffset;
+    }
+
+    public int compareTo(Object o) {
+        int rc = logFileId - ((Location) o).logFileId;
+        if (rc != 0)
+            return rc;
+
+        return logFileOffset - ((Location) o).logFileOffset;
+    }
+
+    public int hashCode() {
+        return logFileOffset ^ logFileId;
+    }
+
+    public boolean equals(Object o) {
+        if (o == null || o.getClass() != Location.class)
+            return false;
+        Location rl = (Location) o;
+        return rl.logFileId == this.logFileId && rl.logFileOffset == this.logFileOffset;
+    }
+
+    public String toString() {
+        return "" + logFileId + ":" + logFileOffset;
+    }
+
+    public int getLogFileId() {
+        return logFileId;
+    }
+
+    public int getLogFileOffset() {
+        return logFileOffset;
+    }
+    
+    public void writeToPacket(Packet packet) throws IOException {
+        PacketData data = new PacketData(packet);
+        data.writeInt(logFileId);
+        data.writeInt(logFileOffset);
+    }
+
+    public void writeToDataOutput(DataOutput data) throws IOException {
+        data.writeInt(logFileId);
+        data.writeInt(logFileOffset);
+    }    
+
+    static public Location readFromPacket(Packet packet) throws IOException {
+        PacketData data = new PacketData(packet);
+        return new Location(data.readInt(), data.readInt());
+    }
+
+    public static Location readFromDataInput(DataInput data) throws IOException {
+        return new Location(data.readInt(), data.readInt());
+    }
+
+    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFile.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFile.java
index feb8e15..18f249c 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFile.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFile.java
@@ -1,153 +1,153 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.File;

-import java.io.FileOutputStream;

-import java.io.IOException;

-import java.io.RandomAccessFile;

-import java.nio.ByteBuffer;

-import java.nio.channels.FileChannel;

-

-/**

- * Allows read/append access to a LogFile.

- * 

- * @version $Revision: 1.1 $

- */

-final public class LogFile {

-

-    private final RandomAccessFile file;

-    private final FileChannel channel;

-

-    /** Prefered size. The size that the log file is set to when initilaized. */

-    private final int initialSize;

-

-    /** Where the we are in the file right now */

-    private int currentOffset;

-	private boolean disposed;

-    

-    public LogFile(File file, int initialSize) throws IOException {

-        this.initialSize = initialSize;

-        boolean initializationNeeeded = !file.exists();

-        this.file = new RandomAccessFile(file, "rw");

-        channel = this.file.getChannel();

-        if( initializationNeeeded )

-            resize();

-        channel.position(0);

-        reloadCurrentOffset();

-    }

-

-    /**

-     * To avoid doing un-needed seeks.

-     */

-    private void seek(int offset) throws IOException {

-        if( offset == currentOffset ) {

-            if( currentOffset != channel.position() )

-                throw new RuntimeException(" "+currentOffset+", "+channel.position() );                

-            return;

-        }

-        channel.position(offset);

-        currentOffset = offset;

-    }

-    private void reloadCurrentOffset() throws IOException {

-        currentOffset= (int) channel.position();

-    }

-    private void addToCurrentOffset(int rc) {

-        currentOffset+=rc;

-    }

-    

-    public boolean loadAndCheckRecord(int offset, Record record) throws IOException {

-        

-        try { 

-            // Read the next header

-            seek(offset);        

-            record.readHeader(file);

-                    

-            if (Record.isChecksumingEnabled()) {

-                record.checksum(file);

-            }            

-            // Load the footer.

-            seek(offset+record.getPayloadLength()+Record.RECORD_HEADER_SIZE);

-            record.readFooter(file);

-            

-            addToCurrentOffset(record.getRecordLength());

-            return true;

-                

-        } catch (IOException e) {

-            reloadCurrentOffset();

-            return false;

-        }

-    }

-    

-    public void resize() throws IOException {

-        file.setLength(initialSize);

-    }

-

-    public void force() throws IOException {

-        channel.force(false);

-    }

-

-    public void dispose() {

-    	if( disposed )

-    		return;

-    	disposed=true;

-        try {

-			this.file.close();

-		} catch (IOException e) {

-		}

-    }

-

-    public void write(int offset, ByteBuffer buffer) throws IOException {

-        

-        try {

-

-            int size = buffer.remaining();

-            seek(offset);

-            while (buffer.hasRemaining()) {

-                channel.write(buffer);                

-            }

-            addToCurrentOffset(size);

-            

-        } catch (IOException e) {

-            reloadCurrentOffset();

-        }

-    }

-

-    public void readRecordHeader(int offset, Record record) throws IOException {

-        seek(offset);  

-        try {

-            record.readHeader(file);

-        } catch ( IOException e ) {

-            reloadCurrentOffset();

-            throw e;

-        }

-        addToCurrentOffset(Record.RECORD_HEADER_SIZE);

-    }

-

-    public void read(int offset, byte[] answer) throws IOException {

-        seek(offset);

-        file.readFully(answer);

-        addToCurrentOffset(answer.length);

-    }

-

-    public void copyTo(File location) throws IOException {

-        FileOutputStream fos = new FileOutputStream(location);

-        channel.transferTo(0, channel.size(), fos.getChannel());

-        fos.getChannel().force(false);

-        fos.close();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+
+/**
+ * Allows read/append access to a LogFile.
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class LogFile {
+
+    private final RandomAccessFile file;
+    private final FileChannel channel;
+
+    /** Prefered size. The size that the log file is set to when initilaized. */
+    private final int initialSize;
+
+    /** Where the we are in the file right now */
+    private int currentOffset;
+	private boolean disposed;
+    
+    public LogFile(File file, int initialSize) throws IOException {
+        this.initialSize = initialSize;
+        boolean initializationNeeeded = !file.exists();
+        this.file = new RandomAccessFile(file, "rw");
+        channel = this.file.getChannel();
+        if( initializationNeeeded )
+            resize();
+        channel.position(0);
+        reloadCurrentOffset();
+    }
+
+    /**
+     * To avoid doing un-needed seeks.
+     */
+    private void seek(int offset) throws IOException {
+        if( offset == currentOffset ) {
+            if( currentOffset != channel.position() )
+                throw new RuntimeException(" "+currentOffset+", "+channel.position() );                
+            return;
+        }
+        channel.position(offset);
+        currentOffset = offset;
+    }
+    private void reloadCurrentOffset() throws IOException {
+        currentOffset= (int) channel.position();
+    }
+    private void addToCurrentOffset(int rc) {
+        currentOffset+=rc;
+    }
+    
+    public boolean loadAndCheckRecord(int offset, Record record) throws IOException {
+        
+        try { 
+            // Read the next header
+            seek(offset);        
+            record.readHeader(file);
+                    
+            if (Record.isChecksumingEnabled()) {
+                record.checksum(file);
+            }            
+            // Load the footer.
+            seek(offset+record.getPayloadLength()+Record.RECORD_HEADER_SIZE);
+            record.readFooter(file);
+            
+            addToCurrentOffset(record.getRecordLength());
+            return true;
+                
+        } catch (IOException e) {
+            reloadCurrentOffset();
+            return false;
+        }
+    }
+    
+    public void resize() throws IOException {
+        file.setLength(initialSize);
+    }
+
+    public void force() throws IOException {
+        channel.force(false);
+    }
+
+    public void dispose() {
+    	if( disposed )
+    		return;
+    	disposed=true;
+        try {
+			this.file.close();
+		} catch (IOException e) {
+		}
+    }
+
+    public void write(int offset, ByteBuffer buffer) throws IOException {
+        
+        try {
+
+            int size = buffer.remaining();
+            seek(offset);
+            while (buffer.hasRemaining()) {
+                channel.write(buffer);                
+            }
+            addToCurrentOffset(size);
+            
+        } catch (IOException e) {
+            reloadCurrentOffset();
+        }
+    }
+
+    public void readRecordHeader(int offset, Record record) throws IOException {
+        seek(offset);  
+        try {
+            record.readHeader(file);
+        } catch ( IOException e ) {
+            reloadCurrentOffset();
+            throw e;
+        }
+        addToCurrentOffset(Record.RECORD_HEADER_SIZE);
+    }
+
+    public void read(int offset, byte[] answer) throws IOException {
+        seek(offset);
+        file.readFully(answer);
+        addToCurrentOffset(answer.length);
+    }
+
+    public void copyTo(File location) throws IOException {
+        FileOutputStream fos = new FileOutputStream(location);
+        channel.transferTo(0, channel.size(), fos.getChannel());
+        fos.getChannel().force(false);
+        fos.close();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileManager.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileManager.java
index 4c79409..d224324 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileManager.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileManager.java
@@ -1,530 +1,530 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.DataInput;

-import java.io.DataInputStream;

-import java.io.DataOutput;

-import java.io.DataOutputStream;

-import java.io.File;

-import java.io.IOException;

-import java.nio.ByteBuffer;

-import java.text.NumberFormat;

-import java.util.HashMap;

-

-import org.apache.activeio.adapter.PacketOutputStream;

-import org.apache.activeio.adapter.PacketToInputStream;

-import org.apache.activeio.journal.InvalidRecordLocationException;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.Packet;

-

-import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;

-

-/**

- * Provides a logical view of many separate files as one single long log file.

- * The separate files that compose the LogFile are Segments of the LogFile.

- * <p/>This class is not thread safe.

- * 

- * @version $Revision: 1.1 $

- */

-final public class LogFileManager {

-

-    public static final int DEFAULT_LOGFILE_COUNT = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultLogFileCount", ""+(2)));

-    public static final int DEFAULT_LOGFILE_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultLogFileSize", ""+(1024*1024*20)));

-

-    static final public int SERIALIZED_SIZE = 6+Location.SERIALIZED_SIZE;

-

-    static final public byte DATA_RECORD_TYPE = 1;

-    static final public byte MARK_RECORD_TYPE = 2;

-    static final private NumberFormat onlineLogNameFormat = NumberFormat.getNumberInstance();

-    static {

-        onlineLogNameFormat.setMinimumIntegerDigits(3);

-        onlineLogNameFormat.setMaximumIntegerDigits(3);

-        onlineLogNameFormat.setGroupingUsed(false);

-        onlineLogNameFormat.setParseIntegerOnly(true);

-        onlineLogNameFormat.setMaximumFractionDigits(0);

-    }

-    

-    static final private NumberFormat archiveLogNameFormat = NumberFormat.getNumberInstance();

-    static {

-        archiveLogNameFormat.setMinimumIntegerDigits(8);

-        archiveLogNameFormat.setMaximumIntegerDigits(8);

-        archiveLogNameFormat.setGroupingUsed(false);

-        archiveLogNameFormat.setParseIntegerOnly(true);

-        archiveLogNameFormat.setMaximumFractionDigits(0);

-    }

-

-    // Config

-    private final File logDirectory;

-    private final int initialLogFileSize;

-    private final int onlineLogFileCount;

-    private final AtomicInteger activeLogFileCount = new AtomicInteger(0);

-    

-    // Keeps track of the online log file.

-    private LogFileNode firstNode;

-    private LogFileNode firstActiveNode;

-    private LogFileNode firstInactiveNode;

-    private LogFileNode appendNode;

-

-    private ControlFile controlFile;

-    private int lastLogFileId = -1;

-    private Location lastMark;

-    private boolean disposed;

-    private boolean loadedFromCleanShutDown;

-    

-    private File archiveDirectory;

-    HashMap openArchivedLogs = new HashMap();

-

-    public LogFileManager(File logDirectory) throws IOException {

-        this(logDirectory, DEFAULT_LOGFILE_COUNT, DEFAULT_LOGFILE_SIZE, null);

-    }

-

-    public LogFileManager(File logDirectory, int onlineLogFileCount, int initialLogFileSize, File archiveDirectory) throws IOException {

-        this.logDirectory = logDirectory;

-        this.onlineLogFileCount = onlineLogFileCount;

-        this.initialLogFileSize = initialLogFileSize;

-        initialize(onlineLogFileCount);

-        this.archiveDirectory=archiveDirectory;

-    }

-

-    void initialize(int onlineLogFileCount) throws IOException {

-

-        LogFileNode logFiles[] = new LogFileNode[onlineLogFileCount];

-

-        // Create the log directory if it does not exist.

-        if (!logDirectory.exists()) {

-            if (!logDirectory.mkdirs()) {

-                throw new IOException("Could not create directory: " + logDirectory);

-            }

-        }

-

-        // Open the control file.        

-        int controlDataSize = SERIALIZED_SIZE + (LogFileNode.SERIALIZED_SIZE*onlineLogFileCount);

-        controlFile = new ControlFile(new File(logDirectory, "control.dat"),  controlDataSize);

-        // Make sure we are the only process using the control file.

-        controlFile.lock();

-        

-        // Initialize the nodes.

-        for (int i = 0; i < onlineLogFileCount; i++) {

-            LogFile file = new LogFile(new File(logDirectory, "log-" + onlineLogNameFormat.format(i) + ".dat"),

-                    initialLogFileSize);

-            logFiles[i] = new LogFileNode(file);

-        }

-

-        // Link the nodes together.

-        for (int i = 0; i < onlineLogFileCount; i++) {

-            if (i == (onlineLogFileCount - 1)) {

-                logFiles[i].setNext(logFiles[0]);

-            } else {

-                logFiles[i].setNext(logFiles[i + 1]);

-            }

-        }

-        

-        firstNode = logFiles[0];

-        loadState();

-

-        // Find the first active node

-        for (int i = 0; i < onlineLogFileCount; i++) {

-            if( logFiles[i].isActive() ) {

-                if( firstActiveNode == null || logFiles[i].getId() < firstActiveNode.getId() ) {

-                    firstActiveNode = logFiles[i];

-                }

-            }

-        }

-        

-        // None was active? activate one.

-        if ( firstActiveNode == null ) {

-            firstInactiveNode = logFiles[0];

-            activateNextLogFile();

-        } else {            

-            // Find the append log and the first inactive node

-            firstInactiveNode = null;

-            LogFileNode log = firstActiveNode;

-            do {

-                if( !log.isActive() ) {

-                    firstInactiveNode = log;

-                    break;

-                } else {

-                    appendNode = log;

-                }

-                log = log.getNext();

-            } while (log != firstActiveNode);

-        }

-        

-        // If we did not have a clean shut down then we have to check the state 

-        // of the append log.

-        if( !this.loadedFromCleanShutDown ) {

-            checkAppendLog();

-        }

-                    

-        loadedFromCleanShutDown = false;

-        storeState();

-    }

-

-    private void checkAppendLog() throws IOException {

-        

-        // We are trying to get the true append offset and the last Mark that was written in 

-        // the append log.

-        

-        int offset = 0;

-        Record record = new Record();

-        LogFile logFile = appendNode.getLogFile();

-        Location markLocation=null;

-        

-        while( logFile.loadAndCheckRecord(offset, record) ) {

-            

-            if( record.getLocation().getLogFileId()!= appendNode.getId() || record.getLocation().getLogFileOffset()!=offset ) {

-                // We must have run past the end of the append location.

-                break;

-            }

-

-            if ( record.getRecordType()==LogFileManager.MARK_RECORD_TYPE) {

-                markLocation = record.getLocation();

-            }

-            

-            offset += record.getRecordLength();            

-        }

-        

-        appendNode.setAppendOffset(offset);

-        

-        if( markLocation!=null ) {

-            try {

-                Packet packet = readPacket(markLocation);

-                markLocation = Location.readFromPacket(packet);

-            } catch (InvalidRecordLocationException e) {

-                throw (IOException)new IOException(e.getMessage()).initCause(e);

-            }

-            updateMark(markLocation);

-        }

-        

-    }

-

-    private void storeState() throws IOException {

-        Packet controlData = controlFile.getControlData();

-        if( controlData.remaining() == 0 )

-            return;

-        

-        DataOutput data = new DataOutputStream(new PacketOutputStream(controlData));

-

-        data.writeInt(lastLogFileId);

-        data.writeBoolean(lastMark!=null);

-        if( lastMark!=null )

-            lastMark.writeToDataOutput(data);

-        data.writeBoolean(loadedFromCleanShutDown);

-        

-        // Load each node's state

-        LogFileNode log = firstNode;

-        do {            

-            log.writeExternal( data );

-            log = log.getNext();

-        } while (log != firstNode);

-        

-        controlFile.store();

-    }

-

-    private void loadState() throws IOException {

-        if( controlFile.load() ) {

-            Packet controlData = controlFile.getControlData();

-            if( controlData.remaining() == 0 )

-                return;

-            

-            DataInput data = new DataInputStream(new PacketToInputStream(controlData));

-    

-            lastLogFileId =data.readInt();

-            if( data.readBoolean() )

-                lastMark = Location.readFromDataInput(data);

-            else

-                lastMark = null;

-            loadedFromCleanShutDown = data.readBoolean();

-    

-            // Load each node's state

-            LogFileNode log = firstNode;

-            do {            

-                log.readExternal( data );

-                log = log.getNext();

-            } while (log != firstNode);

-        }

-    }

-

-    public void dispose() {

-

-        if (disposed)

-            return;

-        this.disposed = true;

-        

-        try {

-	        // Close all the opened log files.

-	        LogFileNode log = firstNode;

-	        do {

-	            log.getLogFile().dispose();

-	            log = log.getNext();

-	        } while (log != firstNode);

-	        

-	        loadedFromCleanShutDown=true;

-	        storeState();

-	        controlFile.dispose();

-        } catch ( IOException e ) {        	

-        }

-        

-    }

-

-    private int getNextLogFileId() {

-        return ++lastLogFileId;

-    }

-

-    /**

-     * @param write

-     * @throws IOException

-     */

-    public void append(BatchedWrite write) throws IOException {

-

-        if (!appendNode.isActive())

-            throw new IllegalStateException("Log file is not active.  Writes are not allowed");

-        if (appendNode.isReadOnly())

-            throw new IllegalStateException("Log file has been marked Read Only.  Writes are not allowed");

-

-        // Write and force the data to disk.

-        LogFile logFile = appendNode.getLogFile();

-        ByteBuffer buffer = ((ByteBufferPacket)write.getPacket().getAdapter(ByteBufferPacket.class)).getByteBuffer();

-        int size = buffer.remaining();

-        logFile.write(appendNode.getAppendOffset(), buffer);

-        if( write.getForce() )

-            logFile.force();

-

-        // Update state

-        appendNode.appended(size);

-        if (write.getMark() != null) {

-            updateMark(write.getMark());

-        }

-    }

-

-    /**

-     * @param write

-     * @throws IOException

-     */

-    synchronized private void updateMark(Location mark) throws IOException {

-        // If we wrote a mark we may need to deactivate some log files.

-        this.lastMark = mark;

-        while (firstActiveNode != appendNode) {

-            if (firstActiveNode.getId() < lastMark.getLogFileId()) {

-                

-                if( archiveDirectory!=null ) {

-                    File file = getArchiveFile(firstActiveNode.getId());

-                    firstActiveNode.getLogFile().copyTo(file);

-                }

-                

-                firstActiveNode.deactivate();

-                activeLogFileCount.decrementAndGet();

-                if( firstInactiveNode == null )

-                    firstInactiveNode = firstActiveNode;

-                firstActiveNode = firstActiveNode.getNextActive();

-                

-            } else {

-                break;

-            }

-        }

-    }

-    

-    private File getArchiveFile(int logId) {

-        return  new File(archiveDirectory, "" + archiveLogNameFormat.format(logId) + ".log");

-    }

-    

-    RecordInfo readRecordInfo(Location location) throws IOException, InvalidRecordLocationException {

-

-        LogFile logFile;

-        LogFileNode logFileState = getLogFileWithId(location.getLogFileId());

-        if( logFileState !=null ) {

-            // There can be no record at the append offset.

-            if (logFileState.getAppendOffset() == location.getLogFileOffset()) {

-                throw new InvalidRecordLocationException("No record at (" + location

-                        + ") found.  Location past end of logged data.");

-            }

-            logFile = logFileState.getLogFile();

-        } else {

-            if( archiveDirectory==null ) {

-                throw new InvalidRecordLocationException("Log file: " + location.getLogFileId() + " is not active.");

-            } else {

-                logFile = getArchivedLogFile(location.getLogFileId());

-            }

-        }

-

-        // Is there a record header at the seeked location?

-        try {

-            Record header = new Record();

-            logFile.readRecordHeader(location.getLogFileOffset(), header);

-            return new RecordInfo(location, header, logFileState, logFile);

-        } catch (IOException e) {

-            throw new InvalidRecordLocationException("No record at (" + location + ") found.");

-        }

-    }

-

-    private LogFile getArchivedLogFile(int logFileId) throws InvalidRecordLocationException, IOException {

-        Integer key = new Integer(logFileId);

-        LogFile rc = (LogFile) openArchivedLogs.get(key);

-        if( rc == null ) {

-            File archiveFile = getArchiveFile(logFileId);

-            if( !archiveFile.canRead() )

-                throw new InvalidRecordLocationException("Log file: " + logFileId + " does not exist.");

-            rc = new LogFile(archiveFile, getInitialLogFileSize());

-            openArchivedLogs.put(key, rc);

-            

-            // TODO: turn openArchivedLogs into LRU cache and close old log files.

-        }

-        return rc;

-    }

-

-    LogFileNode getLogFileWithId(int logFileId) throws InvalidRecordLocationException {

-        for (LogFileNode lf = firstActiveNode; lf != null; lf = lf.getNextActive()) {

-            if (lf.getId() == logFileId) {

-                return lf;

-            }

-

-            // Short cut since id's will only increment

-            if (logFileId < lf.getId())

-                break;

-        }

-        return null;

-    }

-

-    /**

-     * @param lastLocation

-     * @return

-     */

-    public Location getNextDataRecordLocation(Location lastLocation) throws IOException, InvalidRecordLocationException {

-        RecordInfo ri = readRecordInfo(lastLocation);

-        while (true) {

-

-            int logFileId = ri.getLocation().getLogFileId();

-            int offset = ri.getNextLocation();

-

-            // Are we overflowing into next logFile?

-            if (offset >= ri.getLogFileState().getAppendOffset()) {

-                LogFileNode nextActive = ri.getLogFileState().getNextActive();

-                if (nextActive == null) {

-                    return null;

-                }

-                logFileId = nextActive.getId();

-                offset = 0;

-            }

-

-            try {

-                ri = readRecordInfo(new Location(logFileId, offset));

-            } catch (InvalidRecordLocationException e) {

-                return null;

-            }

-

-            // Is the next record the right record type?

-            if (ri.getHeader().getRecordType() == DATA_RECORD_TYPE) {

-                return ri.getLocation();

-            }

-            // No? go onto the next record.

-        }

-    }

-

-    /**

-     * @param logFileIndex

-     * @param logFileOffset

-     * @return

-     * @throws IOException

-     * @throws InvalidRecordLocationException

-     */

-    public Packet readPacket(Location location) throws IOException, InvalidRecordLocationException {

-

-        // Is there a record header at the seeked location?

-        RecordInfo recordInfo = readRecordInfo(location);

-

-        byte data[] = new byte[recordInfo.getHeader().getPayloadLength()];

-

-        LogFile logFile = recordInfo.getLogFile();

-        logFile.read(recordInfo.getDataOffset(), data);

-

-        return new ByteArrayPacket(data);

-

-    }

-

-    public int getInitialLogFileSize() {

-        return initialLogFileSize;

-    }

-

-    public Location getFirstActiveLogLocation() {

-        if (firstActiveNode == null)

-            return null;

-        if (firstActiveNode.getAppendOffset() == 0)

-            return null;

-        return new Location(firstActiveNode.getId(), 0);

-    }

-

-    void activateNextLogFile() throws IOException {

-

-        // The current append logFile becomes readonly

-        if (appendNode != null) {

-            appendNode.setReadOnly(true);

-        }

-

-        LogFileNode next = firstInactiveNode;

-        synchronized (this) {

-            firstInactiveNode = firstInactiveNode.getNextInactive();

-            next.activate(getNextLogFileId());

-            if (firstActiveNode == null) {

-                firstActiveNode = next;

-            }

-        }        

-        activeLogFileCount.incrementAndGet();        

-        appendNode = next;

-        

-        storeState();

-    }

-

-    /**

-     * @return Returns the logDirectory.

-     */

-    public File getLogDirectory() {

-        return logDirectory;

-    }

-

-    /**

-     * @return Returns the lastMark.

-     */

-    public Location getLastMarkedRecordLocation() {

-        return lastMark;

-    }

-

-    public Location getNextAppendLocation() {

-        return new Location(appendNode.getId(), appendNode.getAppendOffset());

-    }

-

-    /**

-     * @return Returns the onlineLogFileCount.

-     */

-    public int getOnlineLogFileCount() {

-        return onlineLogFileCount;

-    }

-

-    public boolean isPastHalfActive() {

-        return (onlineLogFileCount/2.f) < activeLogFileCount.get();

-    }

-

-    synchronized  public Location getFirstRecordLocationOfSecondActiveLogFile() {

-        return firstActiveNode.getNextActive().getFirstRecordLocation();

-    }

-

-    synchronized public boolean canActivateNextLogFile() {

-        return firstInactiveNode!=null;

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.DataInput;
+import java.io.DataInputStream;
+import java.io.DataOutput;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.text.NumberFormat;
+import java.util.HashMap;
+
+import org.apache.activeio.adapter.PacketOutputStream;
+import org.apache.activeio.adapter.PacketToInputStream;
+import org.apache.activeio.journal.InvalidRecordLocationException;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.Packet;
+
+import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Provides a logical view of many separate files as one single long log file.
+ * The separate files that compose the LogFile are Segments of the LogFile.
+ * <p/>This class is not thread safe.
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class LogFileManager {
+
+    public static final int DEFAULT_LOGFILE_COUNT = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultLogFileCount", ""+(2)));
+    public static final int DEFAULT_LOGFILE_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultLogFileSize", ""+(1024*1024*20)));
+
+    static final public int SERIALIZED_SIZE = 6+Location.SERIALIZED_SIZE;
+
+    static final public byte DATA_RECORD_TYPE = 1;
+    static final public byte MARK_RECORD_TYPE = 2;
+    static final private NumberFormat onlineLogNameFormat = NumberFormat.getNumberInstance();
+    static {
+        onlineLogNameFormat.setMinimumIntegerDigits(3);
+        onlineLogNameFormat.setMaximumIntegerDigits(3);
+        onlineLogNameFormat.setGroupingUsed(false);
+        onlineLogNameFormat.setParseIntegerOnly(true);
+        onlineLogNameFormat.setMaximumFractionDigits(0);
+    }
+    
+    static final private NumberFormat archiveLogNameFormat = NumberFormat.getNumberInstance();
+    static {
+        archiveLogNameFormat.setMinimumIntegerDigits(8);
+        archiveLogNameFormat.setMaximumIntegerDigits(8);
+        archiveLogNameFormat.setGroupingUsed(false);
+        archiveLogNameFormat.setParseIntegerOnly(true);
+        archiveLogNameFormat.setMaximumFractionDigits(0);
+    }
+
+    // Config
+    private final File logDirectory;
+    private final int initialLogFileSize;
+    private final int onlineLogFileCount;
+    private final AtomicInteger activeLogFileCount = new AtomicInteger(0);
+    
+    // Keeps track of the online log file.
+    private LogFileNode firstNode;
+    private LogFileNode firstActiveNode;
+    private LogFileNode firstInactiveNode;
+    private LogFileNode appendNode;
+
+    private ControlFile controlFile;
+    private int lastLogFileId = -1;
+    private Location lastMark;
+    private boolean disposed;
+    private boolean loadedFromCleanShutDown;
+    
+    private File archiveDirectory;
+    HashMap openArchivedLogs = new HashMap();
+
+    public LogFileManager(File logDirectory) throws IOException {
+        this(logDirectory, DEFAULT_LOGFILE_COUNT, DEFAULT_LOGFILE_SIZE, null);
+    }
+
+    public LogFileManager(File logDirectory, int onlineLogFileCount, int initialLogFileSize, File archiveDirectory) throws IOException {
+        this.logDirectory = logDirectory;
+        this.onlineLogFileCount = onlineLogFileCount;
+        this.initialLogFileSize = initialLogFileSize;
+        initialize(onlineLogFileCount);
+        this.archiveDirectory=archiveDirectory;
+    }
+
+    void initialize(int onlineLogFileCount) throws IOException {
+
+        LogFileNode logFiles[] = new LogFileNode[onlineLogFileCount];
+
+        // Create the log directory if it does not exist.
+        if (!logDirectory.exists()) {
+            if (!logDirectory.mkdirs()) {
+                throw new IOException("Could not create directory: " + logDirectory);
+            }
+        }
+
+        // Open the control file.        
+        int controlDataSize = SERIALIZED_SIZE + (LogFileNode.SERIALIZED_SIZE*onlineLogFileCount);
+        controlFile = new ControlFile(new File(logDirectory, "control.dat"),  controlDataSize);
+        // Make sure we are the only process using the control file.
+        controlFile.lock();
+        
+        // Initialize the nodes.
+        for (int i = 0; i < onlineLogFileCount; i++) {
+            LogFile file = new LogFile(new File(logDirectory, "log-" + onlineLogNameFormat.format(i) + ".dat"),
+                    initialLogFileSize);
+            logFiles[i] = new LogFileNode(file);
+        }
+
+        // Link the nodes together.
+        for (int i = 0; i < onlineLogFileCount; i++) {
+            if (i == (onlineLogFileCount - 1)) {
+                logFiles[i].setNext(logFiles[0]);
+            } else {
+                logFiles[i].setNext(logFiles[i + 1]);
+            }
+        }
+        
+        firstNode = logFiles[0];
+        loadState();
+
+        // Find the first active node
+        for (int i = 0; i < onlineLogFileCount; i++) {
+            if( logFiles[i].isActive() ) {
+                if( firstActiveNode == null || logFiles[i].getId() < firstActiveNode.getId() ) {
+                    firstActiveNode = logFiles[i];
+                }
+            }
+        }
+        
+        // None was active? activate one.
+        if ( firstActiveNode == null ) {
+            firstInactiveNode = logFiles[0];
+            activateNextLogFile();
+        } else {            
+            // Find the append log and the first inactive node
+            firstInactiveNode = null;
+            LogFileNode log = firstActiveNode;
+            do {
+                if( !log.isActive() ) {
+                    firstInactiveNode = log;
+                    break;
+                } else {
+                    appendNode = log;
+                }
+                log = log.getNext();
+            } while (log != firstActiveNode);
+        }
+        
+        // If we did not have a clean shut down then we have to check the state 
+        // of the append log.
+        if( !this.loadedFromCleanShutDown ) {
+            checkAppendLog();
+        }
+                    
+        loadedFromCleanShutDown = false;
+        storeState();
+    }
+
+    private void checkAppendLog() throws IOException {
+        
+        // We are trying to get the true append offset and the last Mark that was written in 
+        // the append log.
+        
+        int offset = 0;
+        Record record = new Record();
+        LogFile logFile = appendNode.getLogFile();
+        Location markLocation=null;
+        
+        while( logFile.loadAndCheckRecord(offset, record) ) {
+            
+            if( record.getLocation().getLogFileId()!= appendNode.getId() || record.getLocation().getLogFileOffset()!=offset ) {
+                // We must have run past the end of the append location.
+                break;
+            }
+
+            if ( record.getRecordType()==LogFileManager.MARK_RECORD_TYPE) {
+                markLocation = record.getLocation();
+            }
+            
+            offset += record.getRecordLength();            
+        }
+        
+        appendNode.setAppendOffset(offset);
+        
+        if( markLocation!=null ) {
+            try {
+                Packet packet = readPacket(markLocation);
+                markLocation = Location.readFromPacket(packet);
+            } catch (InvalidRecordLocationException e) {
+                throw (IOException)new IOException(e.getMessage()).initCause(e);
+            }
+            updateMark(markLocation);
+        }
+        
+    }
+
+    private void storeState() throws IOException {
+        Packet controlData = controlFile.getControlData();
+        if( controlData.remaining() == 0 )
+            return;
+        
+        DataOutput data = new DataOutputStream(new PacketOutputStream(controlData));
+
+        data.writeInt(lastLogFileId);
+        data.writeBoolean(lastMark!=null);
+        if( lastMark!=null )
+            lastMark.writeToDataOutput(data);
+        data.writeBoolean(loadedFromCleanShutDown);
+        
+        // Load each node's state
+        LogFileNode log = firstNode;
+        do {            
+            log.writeExternal( data );
+            log = log.getNext();
+        } while (log != firstNode);
+        
+        controlFile.store();
+    }
+
+    private void loadState() throws IOException {
+        if( controlFile.load() ) {
+            Packet controlData = controlFile.getControlData();
+            if( controlData.remaining() == 0 )
+                return;
+            
+            DataInput data = new DataInputStream(new PacketToInputStream(controlData));
+    
+            lastLogFileId =data.readInt();
+            if( data.readBoolean() )
+                lastMark = Location.readFromDataInput(data);
+            else
+                lastMark = null;
+            loadedFromCleanShutDown = data.readBoolean();
+    
+            // Load each node's state
+            LogFileNode log = firstNode;
+            do {            
+                log.readExternal( data );
+                log = log.getNext();
+            } while (log != firstNode);
+        }
+    }
+
+    public void dispose() {
+
+        if (disposed)
+            return;
+        this.disposed = true;
+        
+        try {
+	        // Close all the opened log files.
+	        LogFileNode log = firstNode;
+	        do {
+	            log.getLogFile().dispose();
+	            log = log.getNext();
+	        } while (log != firstNode);
+	        
+	        loadedFromCleanShutDown=true;
+	        storeState();
+	        controlFile.dispose();
+        } catch ( IOException e ) {        	
+        }
+        
+    }
+
+    private int getNextLogFileId() {
+        return ++lastLogFileId;
+    }
+
+    /**
+     * @param write
+     * @throws IOException
+     */
+    public void append(BatchedWrite write) throws IOException {
+
+        if (!appendNode.isActive())
+            throw new IllegalStateException("Log file is not active.  Writes are not allowed");
+        if (appendNode.isReadOnly())
+            throw new IllegalStateException("Log file has been marked Read Only.  Writes are not allowed");
+
+        // Write and force the data to disk.
+        LogFile logFile = appendNode.getLogFile();
+        ByteBuffer buffer = ((ByteBufferPacket)write.getPacket().getAdapter(ByteBufferPacket.class)).getByteBuffer();
+        int size = buffer.remaining();
+        logFile.write(appendNode.getAppendOffset(), buffer);
+        if( write.getForce() )
+            logFile.force();
+
+        // Update state
+        appendNode.appended(size);
+        if (write.getMark() != null) {
+            updateMark(write.getMark());
+        }
+    }
+
+    /**
+     * @param write
+     * @throws IOException
+     */
+    synchronized private void updateMark(Location mark) throws IOException {
+        // If we wrote a mark we may need to deactivate some log files.
+        this.lastMark = mark;
+        while (firstActiveNode != appendNode) {
+            if (firstActiveNode.getId() < lastMark.getLogFileId()) {
+                
+                if( archiveDirectory!=null ) {
+                    File file = getArchiveFile(firstActiveNode.getId());
+                    firstActiveNode.getLogFile().copyTo(file);
+                }
+                
+                firstActiveNode.deactivate();
+                activeLogFileCount.decrementAndGet();
+                if( firstInactiveNode == null )
+                    firstInactiveNode = firstActiveNode;
+                firstActiveNode = firstActiveNode.getNextActive();
+                
+            } else {
+                break;
+            }
+        }
+    }
+    
+    private File getArchiveFile(int logId) {
+        return  new File(archiveDirectory, "" + archiveLogNameFormat.format(logId) + ".log");
+    }
+    
+    RecordInfo readRecordInfo(Location location) throws IOException, InvalidRecordLocationException {
+
+        LogFile logFile;
+        LogFileNode logFileState = getLogFileWithId(location.getLogFileId());
+        if( logFileState !=null ) {
+            // There can be no record at the append offset.
+            if (logFileState.getAppendOffset() == location.getLogFileOffset()) {
+                throw new InvalidRecordLocationException("No record at (" + location
+                        + ") found.  Location past end of logged data.");
+            }
+            logFile = logFileState.getLogFile();
+        } else {
+            if( archiveDirectory==null ) {
+                throw new InvalidRecordLocationException("Log file: " + location.getLogFileId() + " is not active.");
+            } else {
+                logFile = getArchivedLogFile(location.getLogFileId());
+            }
+        }
+
+        // Is there a record header at the seeked location?
+        try {
+            Record header = new Record();
+            logFile.readRecordHeader(location.getLogFileOffset(), header);
+            return new RecordInfo(location, header, logFileState, logFile);
+        } catch (IOException e) {
+            throw new InvalidRecordLocationException("No record at (" + location + ") found.");
+        }
+    }
+
+    private LogFile getArchivedLogFile(int logFileId) throws InvalidRecordLocationException, IOException {
+        Integer key = new Integer(logFileId);
+        LogFile rc = (LogFile) openArchivedLogs.get(key);
+        if( rc == null ) {
+            File archiveFile = getArchiveFile(logFileId);
+            if( !archiveFile.canRead() )
+                throw new InvalidRecordLocationException("Log file: " + logFileId + " does not exist.");
+            rc = new LogFile(archiveFile, getInitialLogFileSize());
+            openArchivedLogs.put(key, rc);
+            
+            // TODO: turn openArchivedLogs into LRU cache and close old log files.
+        }
+        return rc;
+    }
+
+    LogFileNode getLogFileWithId(int logFileId) throws InvalidRecordLocationException {
+        for (LogFileNode lf = firstActiveNode; lf != null; lf = lf.getNextActive()) {
+            if (lf.getId() == logFileId) {
+                return lf;
+            }
+
+            // Short cut since id's will only increment
+            if (logFileId < lf.getId())
+                break;
+        }
+        return null;
+    }
+
+    /**
+     * @param lastLocation
+     * @return
+     */
+    public Location getNextDataRecordLocation(Location lastLocation) throws IOException, InvalidRecordLocationException {
+        RecordInfo ri = readRecordInfo(lastLocation);
+        while (true) {
+
+            int logFileId = ri.getLocation().getLogFileId();
+            int offset = ri.getNextLocation();
+
+            // Are we overflowing into next logFile?
+            if (offset >= ri.getLogFileState().getAppendOffset()) {
+                LogFileNode nextActive = ri.getLogFileState().getNextActive();
+                if (nextActive == null) {
+                    return null;
+                }
+                logFileId = nextActive.getId();
+                offset = 0;
+            }
+
+            try {
+                ri = readRecordInfo(new Location(logFileId, offset));
+            } catch (InvalidRecordLocationException e) {
+                return null;
+            }
+
+            // Is the next record the right record type?
+            if (ri.getHeader().getRecordType() == DATA_RECORD_TYPE) {
+                return ri.getLocation();
+            }
+            // No? go onto the next record.
+        }
+    }
+
+    /**
+     * @param logFileIndex
+     * @param logFileOffset
+     * @return
+     * @throws IOException
+     * @throws InvalidRecordLocationException
+     */
+    public Packet readPacket(Location location) throws IOException, InvalidRecordLocationException {
+
+        // Is there a record header at the seeked location?
+        RecordInfo recordInfo = readRecordInfo(location);
+
+        byte data[] = new byte[recordInfo.getHeader().getPayloadLength()];
+
+        LogFile logFile = recordInfo.getLogFile();
+        logFile.read(recordInfo.getDataOffset(), data);
+
+        return new ByteArrayPacket(data);
+
+    }
+
+    public int getInitialLogFileSize() {
+        return initialLogFileSize;
+    }
+
+    public Location getFirstActiveLogLocation() {
+        if (firstActiveNode == null)
+            return null;
+        if (firstActiveNode.getAppendOffset() == 0)
+            return null;
+        return new Location(firstActiveNode.getId(), 0);
+    }
+
+    void activateNextLogFile() throws IOException {
+
+        // The current append logFile becomes readonly
+        if (appendNode != null) {
+            appendNode.setReadOnly(true);
+        }
+
+        LogFileNode next = firstInactiveNode;
+        synchronized (this) {
+            firstInactiveNode = firstInactiveNode.getNextInactive();
+            next.activate(getNextLogFileId());
+            if (firstActiveNode == null) {
+                firstActiveNode = next;
+            }
+        }        
+        activeLogFileCount.incrementAndGet();        
+        appendNode = next;
+        
+        storeState();
+    }
+
+    /**
+     * @return Returns the logDirectory.
+     */
+    public File getLogDirectory() {
+        return logDirectory;
+    }
+
+    /**
+     * @return Returns the lastMark.
+     */
+    public Location getLastMarkedRecordLocation() {
+        return lastMark;
+    }
+
+    public Location getNextAppendLocation() {
+        return new Location(appendNode.getId(), appendNode.getAppendOffset());
+    }
+
+    /**
+     * @return Returns the onlineLogFileCount.
+     */
+    public int getOnlineLogFileCount() {
+        return onlineLogFileCount;
+    }
+
+    public boolean isPastHalfActive() {
+        return (onlineLogFileCount/2.f) < activeLogFileCount.get();
+    }
+
+    synchronized  public Location getFirstRecordLocationOfSecondActiveLogFile() {
+        return firstActiveNode.getNextActive().getFirstRecordLocation();
+    }
+
+    synchronized public boolean canActivateNextLogFile() {
+        return firstInactiveNode!=null;
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileNode.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileNode.java
index ced582a..51c2ab0 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileNode.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/LogFileNode.java
@@ -1,160 +1,160 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.DataInput;

-import java.io.DataOutput;

-import java.io.IOException;

-

-/**

- * @version $Revision: 1.1 $

- */

-final class LogFileNode {

-    

-    static final public int SERIALIZED_SIZE = 10;

-

-    private final LogFile logFile;    

-    private LogFileNode next;

-

-    /** The id of the log file. */

-    private int id;

-    /** Does it have live records in it? */

-    private boolean active = false;

-    /** Is the log file in readonly mode */

-    private boolean readOnly;

-    /** The location of the next append offset */

-    private int appendOffset = 0;

-

-    public LogFileNode(LogFile logFile) {

-        this.logFile = logFile;

-    }

-

-    public LogFile getLogFile() {

-        return logFile;

-    }

-

-    /////////////////////////////////////////////////////////////

-    //

-    // Method used to mange the state of the log file.

-    //

-    /////////////////////////////////////////////////////////////

-

-    public void activate(int id) {

-        if (active)

-            throw new IllegalStateException("Log already active.");

-        this.id = id;

-        this.readOnly = false;

-        this.active = true;

-        this.appendOffset = 0;

-    }

-

-    public int getId() {

-        return id;

-    }

-

-    public void setReadOnly(boolean enable) {

-        if (!active)

-            throw new IllegalStateException("Log not active.");

-        this.readOnly = enable;

-    }

-

-    public void deactivate() throws IOException {

-        if (!active)

-            throw new IllegalStateException("Log already inactive.");      

-        this.active=false; 

-        this.id = -1;

-        this.readOnly = true;

-        this.appendOffset = 0;

-        getLogFile().resize();

-    }

-

-    public boolean isActive() {

-        return active;

-    }

-

-    public int getAppendOffset() {

-        return appendOffset;

-    }

-

-    public Location getFirstRecordLocation() {

-        if (isActive() && appendOffset > 0)

-            return new Location(getId(), 0);

-        return null;

-    }

-

-    public boolean isReadOnly() {

-        return readOnly;

-    }

-

-    public void appended(int i) {

-        appendOffset += i;

-    }

-    

-    /////////////////////////////////////////////////////////////

-    //

-    // Method used to maintain the list of LogFileNodes used by 

-    // the LogFileManager

-    //

-    /////////////////////////////////////////////////////////////

-    

-    public LogFileNode getNext() {

-        return next;

-    }

-

-    public void setNext(LogFileNode state) {

-        next = state;

-    }

-

-    public LogFileNode getNextActive() {

-        if (getNext().isActive())

-            return getNext();

-        return null;

-    }

-

-    public LogFileNode getNextInactive() {

-        if (!getNext().isActive())

-            return getNext();

-        return null;

-    }

-    

-    /**

-     * @param data

-     * @throws IOException 

-     */

-    public void writeExternal(DataOutput data) throws IOException {

-        data.writeInt(id);

-        data.writeBoolean(active);

-        data.writeBoolean(readOnly);

-        data.writeInt(appendOffset);

-    }

-

-    /**

-     * @param data

-     * @throws IOException 

-     */

-    public void readExternal(DataInput data) throws IOException {

-        id = data.readInt();

-        active = data.readBoolean();

-        readOnly = data.readBoolean();

-        appendOffset = data.readInt();

-    }

-

-    public void setAppendOffset(int offset) {

-        appendOffset = offset;

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+
+/**
+ * @version $Revision: 1.1 $
+ */
+final class LogFileNode {
+    
+    static final public int SERIALIZED_SIZE = 10;
+
+    private final LogFile logFile;    
+    private LogFileNode next;
+
+    /** The id of the log file. */
+    private int id;
+    /** Does it have live records in it? */
+    private boolean active = false;
+    /** Is the log file in readonly mode */
+    private boolean readOnly;
+    /** The location of the next append offset */
+    private int appendOffset = 0;
+
+    public LogFileNode(LogFile logFile) {
+        this.logFile = logFile;
+    }
+
+    public LogFile getLogFile() {
+        return logFile;
+    }
+
+    /////////////////////////////////////////////////////////////
+    //
+    // Method used to mange the state of the log file.
+    //
+    /////////////////////////////////////////////////////////////
+
+    public void activate(int id) {
+        if (active)
+            throw new IllegalStateException("Log already active.");
+        this.id = id;
+        this.readOnly = false;
+        this.active = true;
+        this.appendOffset = 0;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setReadOnly(boolean enable) {
+        if (!active)
+            throw new IllegalStateException("Log not active.");
+        this.readOnly = enable;
+    }
+
+    public void deactivate() throws IOException {
+        if (!active)
+            throw new IllegalStateException("Log already inactive.");      
+        this.active=false; 
+        this.id = -1;
+        this.readOnly = true;
+        this.appendOffset = 0;
+        getLogFile().resize();
+    }
+
+    public boolean isActive() {
+        return active;
+    }
+
+    public int getAppendOffset() {
+        return appendOffset;
+    }
+
+    public Location getFirstRecordLocation() {
+        if (isActive() && appendOffset > 0)
+            return new Location(getId(), 0);
+        return null;
+    }
+
+    public boolean isReadOnly() {
+        return readOnly;
+    }
+
+    public void appended(int i) {
+        appendOffset += i;
+    }
+    
+    /////////////////////////////////////////////////////////////
+    //
+    // Method used to maintain the list of LogFileNodes used by 
+    // the LogFileManager
+    //
+    /////////////////////////////////////////////////////////////
+    
+    public LogFileNode getNext() {
+        return next;
+    }
+
+    public void setNext(LogFileNode state) {
+        next = state;
+    }
+
+    public LogFileNode getNextActive() {
+        if (getNext().isActive())
+            return getNext();
+        return null;
+    }
+
+    public LogFileNode getNextInactive() {
+        if (!getNext().isActive())
+            return getNext();
+        return null;
+    }
+    
+    /**
+     * @param data
+     * @throws IOException 
+     */
+    public void writeExternal(DataOutput data) throws IOException {
+        data.writeInt(id);
+        data.writeBoolean(active);
+        data.writeBoolean(readOnly);
+        data.writeInt(appendOffset);
+    }
+
+    /**
+     * @param data
+     * @throws IOException 
+     */
+    public void readExternal(DataInput data) throws IOException {
+        id = data.readInt();
+        active = data.readBoolean();
+        readOnly = data.readBoolean();
+        appendOffset = data.readInt();
+    }
+
+    public void setAppendOffset(int offset) {
+        appendOffset = offset;
+    }
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/Record.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/Record.java
index c6e8c8d..a4d064d 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/Record.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/Record.java
@@ -1,307 +1,307 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.DataInput;

-import java.io.DataInputStream;

-import java.io.DataOutput;

-import java.io.DataOutputStream;

-import java.io.IOException;

-import java.util.zip.CRC32;

-

-import org.apache.activeio.adapter.PacketOutputStream;

-import org.apache.activeio.adapter.PacketToInputStream;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-

-

-/**

- * Serializes/Deserializes data records. 

- * 

- * @version $Revision: 1.1 $

- */

-final public class Record {

-    

-    static final public int RECORD_HEADER_SIZE=8+Location.SERIALIZED_SIZE;

-    static final public int RECORD_FOOTER_SIZE=12+Location.SERIALIZED_SIZE;

-	static final public int RECORD_BASE_SIZE=RECORD_HEADER_SIZE+RECORD_FOOTER_SIZE;

-	

-    static final public byte[] START_OF_RECORD 	= new byte[] { 'S', 'o', 'R' }; 

-    static final public byte[] END_OF_RECORD 	= new byte[] { 'E', 'o', 'R', '.' }; 

-        

-	static final public int SELECTED_CHECKSUM_ALGORITHIM;

-	static final public int NO_CHECKSUM_ALGORITHIM=0;

-	static final public int HASH_CHECKSUM_ALGORITHIM=1;

-	static final public int CRC32_CHECKSUM_ALGORITHIM=2;

-	

-	static {

-		String type = System.getProperty("org.apache.activeio.journal.active.SELECTED_CHECKSUM_ALGORITHIM", "none");

-		if( "none".equals(type) ) {

-			SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM;			

-		} else if( "crc32".equals(type) ) {

-			SELECTED_CHECKSUM_ALGORITHIM = CRC32_CHECKSUM_ALGORITHIM;			

-		} else if( "hash".equals(type) ) {

-			SELECTED_CHECKSUM_ALGORITHIM = HASH_CHECKSUM_ALGORITHIM;			

-		} else {

-			System.err.println("System property 'org.apache.activeio.journal.active.SELECTED_CHECKSUM_ALGORITHIM' not set properly.  Valid values are: 'none', 'hash', or 'crc32'");

-			SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM;			

-		}

-	}

-	

-	static public boolean isChecksumingEnabled() {

-		return SELECTED_CHECKSUM_ALGORITHIM!=NO_CHECKSUM_ALGORITHIM;

-	}

-		    

-    private final ByteArrayPacket headerFooterPacket = new ByteArrayPacket(new byte[RECORD_BASE_SIZE]);

-    private final DataOutputStream headerFooterData = new DataOutputStream(new PacketOutputStream(headerFooterPacket));

-

-    private int payloadLength;

-    private Location location;

-    private byte recordType;        

-    private long checksum;	

-    private Location mark;

-    private Packet payload;

- 		

-    public Record() {        

-    }

-

-    public Record(byte recordType, Packet payload, Location mark) throws IOException {

-        this(null, recordType, payload, mark);

-    }

-    

-    public Record(Location location, byte recordType, Packet payload, Location mark) throws IOException {

-        this.location = location;

-        this.recordType = recordType;

-        this.mark = mark;

-        this.payload = payload.slice();

-        this.payloadLength = payload.remaining();

-        if( isChecksumingEnabled() ) {

-            checksum(new DataInputStream(new PacketToInputStream(this.payload)));

-        }

-

-        writeHeader(headerFooterData);

-        writeFooter(headerFooterData);

-    }    

-    

-    public void setLocation(Location location) throws IOException {

-        this.location = location;

-        headerFooterPacket.clear();

-        headerFooterPacket.position(8);

-        location.writeToDataOutput(headerFooterData);

-        headerFooterPacket.position(RECORD_HEADER_SIZE+8);

-        location.writeToDataOutput(headerFooterData);

-        payload.clear();

-        headerFooterPacket.position(0);

-        headerFooterPacket.limit(RECORD_HEADER_SIZE);

-    }

-    

-	private void writeHeader( DataOutput out ) throws IOException {

-	    out.write(START_OF_RECORD);

-	    out.writeByte(recordType);

-	    out.writeInt(payloadLength);

-        if( location!=null )

-            location.writeToDataOutput(out);

-        else

-            out.writeLong(0);

-	}	

-	

-	public void readHeader( DataInput in ) throws IOException {

-        readAndCheckConstant(in, START_OF_RECORD, "Invalid record header: start of record constant missing.");

-        recordType = in.readByte();

-        payloadLength = in.readInt();

-        if( payloadLength < 0 )

-            throw new IOException("Invalid record header: record length cannot be less than zero.");

-        location = Location.readFromDataInput(in);

-	}

-	

-	private void writeFooter( DataOutput out ) throws IOException {

-	    out.writeLong(checksum);

-        if( location!=null )

-            location.writeToDataOutput(out);

-        else

-            out.writeLong(0);

-	    out.write(END_OF_RECORD);

-	}

-	

-	public void readFooter( DataInput in ) throws IOException {

-	    long l = in.readLong();	    

-        if( isChecksumingEnabled() ) {

-            if( l!=checksum )            

-                throw new IOException("Invalid record footer: checksum does not match.");

-        } else {

-            checksum = l;            

-        }

-        

-        Location loc = Location.readFromDataInput(in);

-        if( !loc.equals(location) )

-            throw new IOException("Invalid record footer: location id does not match.");

-        

-        readAndCheckConstant(in, END_OF_RECORD, "Invalid record header: end of record constant missing.");

-	}

-	

-    /**

-     * @param randomAccessFile

-     * @throws IOException

-     */

-	public void checksum(DataInput in) throws IOException {

-		if( SELECTED_CHECKSUM_ALGORITHIM==HASH_CHECKSUM_ALGORITHIM ) {

-

-		    byte  buffer[] = new byte[1024];

-			byte rc[] = new byte[8];

-			for (int i = 0; i < payloadLength;) {

-			    int l = Math.min(buffer.length, payloadLength-i);

-				in.readFully(buffer,0,l);

-				for (int j = 0; j < l; j++) {

-					rc[j%8] ^= buffer[j];			

-				}

-				i+=l;

-			}			

-			checksum = (rc[0])|(rc[1]<<1)|(rc[2]<<2)|(rc[3]<<3)|(rc[4]<<4)|(rc[5]<<5)|(rc[6]<<6)|(rc[7]<<7) ;

-			

-		} else if( SELECTED_CHECKSUM_ALGORITHIM==CRC32_CHECKSUM_ALGORITHIM ) {

-			byte  buffer[] = new byte[1024];

-			CRC32 crc32 = new CRC32();

-			for (int i = 0; i < payloadLength;) {

-			    int l = Math.min(buffer.length, payloadLength-i);

-				in.readFully(buffer,0,l);

-				crc32.update(buffer,0,l);

-				i+=l;

-			}			

-			checksum = crc32.getValue();

-		} else {

-		    checksum = 0L;

-		}

-    }

-

-	

-    /**

-     */

-    private void readAndCheckConstant(DataInput in, byte[] byteConstant, String errorMessage ) throws IOException {

-        for (int i = 0; i < byteConstant.length; i++) {

-            byte checkByte = byteConstant[i];

-            if( in.readByte()!= checkByte ) {

-                throw new IOException(errorMessage);

-            }

-        }

-    }    

-    

-    public boolean readFromPacket(Packet packet) throws IOException {

-        Packet dup = packet.duplicate();

-

-        if( dup.remaining() < RECORD_HEADER_SIZE )

-            return false;

-        DataInputStream is = new DataInputStream(new PacketToInputStream(dup));

-        readHeader( is );

-        if( dup.remaining() < payloadLength+RECORD_FOOTER_SIZE ) {

-            return false;

-        }

-        

-        // Set limit to create a slice of the payload.

-        dup.limit(dup.position()+payloadLength);

-        this.payload = dup.slice();        

-	    if( isChecksumingEnabled() ) {

-	        checksum(new DataInputStream(new PacketToInputStream(payload)));

-	    }

-	    

-	    // restore the limit and seek to the footer.

-        dup.limit(packet.limit());

-        dup.position(dup.position()+payloadLength);

-        readFooter(is);

-        

-        // If every thing went well.. advance the position of the orignal packet.

-        packet.position(dup.position());

-        dup.dispose();

-        return true;        

-    }

-    

-    /**

-     * @return Returns the checksum.

-     */

-    public long getChecksum() {

-        return checksum;

-    }

-

-    /**

-     * @return Returns the length.

-     */

-    public int getPayloadLength() {

-        return payloadLength;

-    }

-

-    /**

-     * @return Returns the length of the record .

-     */

-    public int getRecordLength() {

-        return payloadLength+Record.RECORD_BASE_SIZE;

-    }

-

-    /**

-     * @return Returns the location.

-     */

-    public Location getLocation() {

-        return location;

-    }

-    

-    /**

-     * @return Returns the mark.

-     */

-    public Location getMark() {

-        return mark;

-    }

-

-    /**

-     * @return Returns the payload.

-     */

-    public Packet getPayload() {

-        return payload;

-    }

-

-    /**

-     * @return Returns the recordType.

-     */

-    public byte getRecordType() {

-        return recordType;

-    }

-

-	public boolean hasRemaining() {

-		return headerFooterPacket.position()!=RECORD_BASE_SIZE;

-	}

-

-	public void read(Packet packet) {

-		

-		// push the header

-		headerFooterPacket.read(packet);

-		// push the payload.

-		payload.read(packet);

-		

-		// Can we switch to the footer now?

-		if( !payload.hasRemaining() && headerFooterPacket.position()==RECORD_HEADER_SIZE ) {

-			headerFooterPacket.position(RECORD_HEADER_SIZE);

-             headerFooterPacket.limit(RECORD_BASE_SIZE);

-			headerFooterPacket.read(packet);			

-		}

-		

-	}

-

-    public void dispose() {

-        if( payload!=null ) {

-            payload.dispose();

-            payload=null;

-        }

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.DataInput;
+import java.io.DataInputStream;
+import java.io.DataOutput;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.zip.CRC32;
+
+import org.apache.activeio.adapter.PacketOutputStream;
+import org.apache.activeio.adapter.PacketToInputStream;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ * Serializes/Deserializes data records. 
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class Record {
+    
+    static final public int RECORD_HEADER_SIZE=8+Location.SERIALIZED_SIZE;
+    static final public int RECORD_FOOTER_SIZE=12+Location.SERIALIZED_SIZE;
+	static final public int RECORD_BASE_SIZE=RECORD_HEADER_SIZE+RECORD_FOOTER_SIZE;
+	
+    static final public byte[] START_OF_RECORD 	= new byte[] { 'S', 'o', 'R' }; 
+    static final public byte[] END_OF_RECORD 	= new byte[] { 'E', 'o', 'R', '.' }; 
+        
+	static final public int SELECTED_CHECKSUM_ALGORITHIM;
+	static final public int NO_CHECKSUM_ALGORITHIM=0;
+	static final public int HASH_CHECKSUM_ALGORITHIM=1;
+	static final public int CRC32_CHECKSUM_ALGORITHIM=2;
+	
+	static {
+		String type = System.getProperty("org.apache.activeio.journal.active.SELECTED_CHECKSUM_ALGORITHIM", "none");
+		if( "none".equals(type) ) {
+			SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM;			
+		} else if( "crc32".equals(type) ) {
+			SELECTED_CHECKSUM_ALGORITHIM = CRC32_CHECKSUM_ALGORITHIM;			
+		} else if( "hash".equals(type) ) {
+			SELECTED_CHECKSUM_ALGORITHIM = HASH_CHECKSUM_ALGORITHIM;			
+		} else {
+			System.err.println("System property 'org.apache.activeio.journal.active.SELECTED_CHECKSUM_ALGORITHIM' not set properly.  Valid values are: 'none', 'hash', or 'crc32'");
+			SELECTED_CHECKSUM_ALGORITHIM = NO_CHECKSUM_ALGORITHIM;			
+		}
+	}
+	
+	static public boolean isChecksumingEnabled() {
+		return SELECTED_CHECKSUM_ALGORITHIM!=NO_CHECKSUM_ALGORITHIM;
+	}
+		    
+    private final ByteArrayPacket headerFooterPacket = new ByteArrayPacket(new byte[RECORD_BASE_SIZE]);
+    private final DataOutputStream headerFooterData = new DataOutputStream(new PacketOutputStream(headerFooterPacket));
+
+    private int payloadLength;
+    private Location location;
+    private byte recordType;        
+    private long checksum;	
+    private Location mark;
+    private Packet payload;
+ 		
+    public Record() {        
+    }
+
+    public Record(byte recordType, Packet payload, Location mark) throws IOException {
+        this(null, recordType, payload, mark);
+    }
+    
+    public Record(Location location, byte recordType, Packet payload, Location mark) throws IOException {
+        this.location = location;
+        this.recordType = recordType;
+        this.mark = mark;
+        this.payload = payload.slice();
+        this.payloadLength = payload.remaining();
+        if( isChecksumingEnabled() ) {
+            checksum(new DataInputStream(new PacketToInputStream(this.payload)));
+        }
+
+        writeHeader(headerFooterData);
+        writeFooter(headerFooterData);
+    }    
+    
+    public void setLocation(Location location) throws IOException {
+        this.location = location;
+        headerFooterPacket.clear();
+        headerFooterPacket.position(8);
+        location.writeToDataOutput(headerFooterData);
+        headerFooterPacket.position(RECORD_HEADER_SIZE+8);
+        location.writeToDataOutput(headerFooterData);
+        payload.clear();
+        headerFooterPacket.position(0);
+        headerFooterPacket.limit(RECORD_HEADER_SIZE);
+    }
+    
+	private void writeHeader( DataOutput out ) throws IOException {
+	    out.write(START_OF_RECORD);
+	    out.writeByte(recordType);
+	    out.writeInt(payloadLength);
+        if( location!=null )
+            location.writeToDataOutput(out);
+        else
+            out.writeLong(0);
+	}	
+	
+	public void readHeader( DataInput in ) throws IOException {
+        readAndCheckConstant(in, START_OF_RECORD, "Invalid record header: start of record constant missing.");
+        recordType = in.readByte();
+        payloadLength = in.readInt();
+        if( payloadLength < 0 )
+            throw new IOException("Invalid record header: record length cannot be less than zero.");
+        location = Location.readFromDataInput(in);
+	}
+	
+	private void writeFooter( DataOutput out ) throws IOException {
+	    out.writeLong(checksum);
+        if( location!=null )
+            location.writeToDataOutput(out);
+        else
+            out.writeLong(0);
+	    out.write(END_OF_RECORD);
+	}
+	
+	public void readFooter( DataInput in ) throws IOException {
+	    long l = in.readLong();	    
+        if( isChecksumingEnabled() ) {
+            if( l!=checksum )            
+                throw new IOException("Invalid record footer: checksum does not match.");
+        } else {
+            checksum = l;            
+        }
+        
+        Location loc = Location.readFromDataInput(in);
+        if( !loc.equals(location) )
+            throw new IOException("Invalid record footer: location id does not match.");
+        
+        readAndCheckConstant(in, END_OF_RECORD, "Invalid record header: end of record constant missing.");
+	}
+	
+    /**
+     * @param randomAccessFile
+     * @throws IOException
+     */
+	public void checksum(DataInput in) throws IOException {
+		if( SELECTED_CHECKSUM_ALGORITHIM==HASH_CHECKSUM_ALGORITHIM ) {
+
+		    byte  buffer[] = new byte[1024];
+			byte rc[] = new byte[8];
+			for (int i = 0; i < payloadLength;) {
+			    int l = Math.min(buffer.length, payloadLength-i);
+				in.readFully(buffer,0,l);
+				for (int j = 0; j < l; j++) {
+					rc[j%8] ^= buffer[j];			
+				}
+				i+=l;
+			}			
+			checksum = (rc[0])|(rc[1]<<1)|(rc[2]<<2)|(rc[3]<<3)|(rc[4]<<4)|(rc[5]<<5)|(rc[6]<<6)|(rc[7]<<7) ;
+			
+		} else if( SELECTED_CHECKSUM_ALGORITHIM==CRC32_CHECKSUM_ALGORITHIM ) {
+			byte  buffer[] = new byte[1024];
+			CRC32 crc32 = new CRC32();
+			for (int i = 0; i < payloadLength;) {
+			    int l = Math.min(buffer.length, payloadLength-i);
+				in.readFully(buffer,0,l);
+				crc32.update(buffer,0,l);
+				i+=l;
+			}			
+			checksum = crc32.getValue();
+		} else {
+		    checksum = 0L;
+		}
+    }
+
+	
+    /**
+     */
+    private void readAndCheckConstant(DataInput in, byte[] byteConstant, String errorMessage ) throws IOException {
+        for (int i = 0; i < byteConstant.length; i++) {
+            byte checkByte = byteConstant[i];
+            if( in.readByte()!= checkByte ) {
+                throw new IOException(errorMessage);
+            }
+        }
+    }    
+    
+    public boolean readFromPacket(Packet packet) throws IOException {
+        Packet dup = packet.duplicate();
+
+        if( dup.remaining() < RECORD_HEADER_SIZE )
+            return false;
+        DataInputStream is = new DataInputStream(new PacketToInputStream(dup));
+        readHeader( is );
+        if( dup.remaining() < payloadLength+RECORD_FOOTER_SIZE ) {
+            return false;
+        }
+        
+        // Set limit to create a slice of the payload.
+        dup.limit(dup.position()+payloadLength);
+        this.payload = dup.slice();        
+	    if( isChecksumingEnabled() ) {
+	        checksum(new DataInputStream(new PacketToInputStream(payload)));
+	    }
+	    
+	    // restore the limit and seek to the footer.
+        dup.limit(packet.limit());
+        dup.position(dup.position()+payloadLength);
+        readFooter(is);
+        
+        // If every thing went well.. advance the position of the orignal packet.
+        packet.position(dup.position());
+        dup.dispose();
+        return true;        
+    }
+    
+    /**
+     * @return Returns the checksum.
+     */
+    public long getChecksum() {
+        return checksum;
+    }
+
+    /**
+     * @return Returns the length.
+     */
+    public int getPayloadLength() {
+        return payloadLength;
+    }
+
+    /**
+     * @return Returns the length of the record .
+     */
+    public int getRecordLength() {
+        return payloadLength+Record.RECORD_BASE_SIZE;
+    }
+
+    /**
+     * @return Returns the location.
+     */
+    public Location getLocation() {
+        return location;
+    }
+    
+    /**
+     * @return Returns the mark.
+     */
+    public Location getMark() {
+        return mark;
+    }
+
+    /**
+     * @return Returns the payload.
+     */
+    public Packet getPayload() {
+        return payload;
+    }
+
+    /**
+     * @return Returns the recordType.
+     */
+    public byte getRecordType() {
+        return recordType;
+    }
+
+	public boolean hasRemaining() {
+		return headerFooterPacket.position()!=RECORD_BASE_SIZE;
+	}
+
+	public void read(Packet packet) {
+		
+		// push the header
+		headerFooterPacket.read(packet);
+		// push the payload.
+		payload.read(packet);
+		
+		// Can we switch to the footer now?
+		if( !payload.hasRemaining() && headerFooterPacket.position()==RECORD_HEADER_SIZE ) {
+			headerFooterPacket.position(RECORD_HEADER_SIZE);
+             headerFooterPacket.limit(RECORD_BASE_SIZE);
+			headerFooterPacket.read(packet);			
+		}
+		
+	}
+
+    public void dispose() {
+        if( payload!=null ) {
+            payload.dispose();
+            payload=null;
+        }
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/active/RecordInfo.java b/activeio-core/src/main/java/org/apache/activeio/journal/active/RecordInfo.java
index 3c5bd42..6316961 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/active/RecordInfo.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/active/RecordInfo.java
@@ -1,59 +1,59 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-/**

- * @version $Revision: 1.1 $

- */

-final public class RecordInfo {

-

-    private final Location location;

-    private final Record header;

-    private final LogFileNode logFileState;

-    private final LogFile logFile;

-

-    public RecordInfo(Location location, Record header, LogFileNode logFileState, LogFile logFile) {

-        this.location = location;

-        this.header = header;

-        this.logFileState = logFileState;

-        this.logFile = logFile;

-    }

-

-    int getNextLocation() {

-        return location.getLogFileOffset() + header.getPayloadLength() + Record.RECORD_BASE_SIZE;

-    }

-

-    public Record getHeader() {

-        return header;

-    }

-

-    public Location getLocation() {

-        return location;

-    }

-

-    public LogFileNode getLogFileState() {

-        return logFileState;

-    }

-

-    public LogFile getLogFile() {

-        return logFile;

-    }

-

-    public int getDataOffset() {

-        return location.getLogFileOffset() + Record.RECORD_HEADER_SIZE;

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+/**
+ * @version $Revision: 1.1 $
+ */
+final public class RecordInfo {
+
+    private final Location location;
+    private final Record header;
+    private final LogFileNode logFileState;
+    private final LogFile logFile;
+
+    public RecordInfo(Location location, Record header, LogFileNode logFileState, LogFile logFile) {
+        this.location = location;
+        this.header = header;
+        this.logFileState = logFileState;
+        this.logFile = logFile;
+    }
+
+    int getNextLocation() {
+        return location.getLogFileOffset() + header.getPayloadLength() + Record.RECORD_BASE_SIZE;
+    }
+
+    public Record getHeader() {
+        return header;
+    }
+
+    public Location getLocation() {
+        return location;
+    }
+
+    public LogFileNode getLogFileState() {
+        return logFileState;
+    }
+
+    public LogFile getLogFile() {
+        return logFile;
+    }
+
+    public int getDataOffset() {
+        return location.getLogFileOffset() + Record.RECORD_HEADER_SIZE;
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/howl/HowlJournal.java b/activeio-core/src/main/java/org/apache/activeio/journal/howl/HowlJournal.java
index 592df98..19c9eb5 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/howl/HowlJournal.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/howl/HowlJournal.java
@@ -1,201 +1,201 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.howl;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-

-import org.apache.activeio.journal.InvalidRecordLocationException;

-import org.apache.activeio.journal.Journal;

-import org.apache.activeio.journal.JournalEventListener;

-import org.apache.activeio.journal.RecordLocation;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-import org.objectweb.howl.log.Configuration;

-import org.objectweb.howl.log.InvalidFileSetException;

-import org.objectweb.howl.log.InvalidLogBufferException;

-import org.objectweb.howl.log.InvalidLogKeyException;

-import org.objectweb.howl.log.LogConfigurationException;

-import org.objectweb.howl.log.LogEventListener;

-import org.objectweb.howl.log.LogRecord;

-import org.objectweb.howl.log.Logger;

-

-/**

- * An implementation of the Journal interface using a HOWL logger.  This is is a thin

- * wrapper around a HOWL logger.

- * 

- * This implementation can be used to write records but not to retreive them

- * yet. Once the HOWL logger implements the methods needed to retreive

- * previously stored records, this class can be completed.

- * 

- * @version $Revision: 1.2 $

- */

-public class HowlJournal implements Journal {

-

-	private final Logger logger;

-

-	private RecordLocation lastMark;

-

-	public HowlJournal(Configuration configuration)

-			throws InvalidFileSetException, LogConfigurationException,

-			InvalidLogBufferException, ClassNotFoundException, IOException,

-			InterruptedException {

-		this.logger = new Logger(configuration);

-		this.logger.open();

-		lastMark = new LongRecordLocation(logger.getActiveMark());

-	}

-

-	/**

-	 * @see org.apache.activeio.journal.Journal#write(byte[], boolean)

-	 */

-	public RecordLocation write(Packet packet, boolean sync) throws IOException {

-		try {

-			return new LongRecordLocation(logger.put(packet.sliceAsBytes(), sync));

-		} catch (InterruptedException e) {

-			throw (InterruptedIOException) new InterruptedIOException()

-					.initCause(e);

-		} catch (IOException e) {

-			throw e;

-		} catch (Exception e) {

-			throw (IOException) new IOException("Journal write failed: " + e)

-					.initCause(e);

-		}

-	}

-

-	/**

-	 * @see org.apache.activeio.journal.Journal#setMark(org.codehaus.activemq.journal.RecordLocation, boolean)

-	 */

-	public void setMark(RecordLocation recordLocator, boolean force)

-			throws InvalidRecordLocationException, IOException {

-		try {

-			long location = toLong(recordLocator);

-			logger.mark(location, force);

-			lastMark = recordLocator;

-

-		} catch (InterruptedException e) {

-			throw (InterruptedIOException) new InterruptedIOException()

-					.initCause(e);

-		} catch (IOException e) {

-			throw e;

-		} catch (InvalidLogKeyException e) {

-			throw new InvalidRecordLocationException(e.getMessage(), e);

-		} catch (Exception e) {

-			throw (IOException) new IOException("Journal write failed: " + e)

-					.initCause(e);

-		}

-	}

-	

-	/**

-     * @param recordLocator

-     * @return

-     * @throws InvalidRecordLocationException

-     */

-    private long toLong(RecordLocation recordLocator) throws InvalidRecordLocationException {

-        if (recordLocator == null

-        		|| recordLocator.getClass() != LongRecordLocation.class)

-        	throw new InvalidRecordLocationException();

-

-        long location = ((LongRecordLocation) recordLocator)

-        		.getLongLocation();

-        return location;

-    }

-

-    /**

-	 * @see org.apache.activeio.journal.Journal#getMark()

-	 */

-	public RecordLocation getMark() {

-		return lastMark;

-	}

-

-	/**

-	 * @see org.apache.activeio.journal.Journal#close()

-	 */

-	public void close() throws IOException {

-		try {

-			logger.close();

-		} catch (IOException e) {

-			throw e;

-		} catch (InterruptedException e) {

-			throw (InterruptedIOException) new InterruptedIOException()

-					.initCause(e);

-		} catch (Exception e) {

-			throw (IOException) new IOException("Journal close failed: " + e)

-					.initCause(e);

-		}

-	}

-

-	/**

-	 * @see org.apache.activeio.journal.Journal#setJournalEventListener(org.codehaus.activemq.journal.JournalEventListener)

-	 */

-	public void setJournalEventListener(final JournalEventListener eventListener) {

-		logger.setLogEventListener(new LogEventListener() {

-			public void logOverflowNotification(long key) {

-				eventListener.overflowNotification(new LongRecordLocation(key));

-			}

-		});

-	}

-

-	/**

-	 * @see org.apache.activeio.journal.Journal#getNextRecordLocation(org.codehaus.activemq.journal.RecordLocation)

-	 */

-	public RecordLocation getNextRecordLocation(RecordLocation lastLocation)

-			throws InvalidRecordLocationException {

-	    

-	    if( lastLocation ==null ) {

-	        if( this.lastMark !=null ) {

-	            lastLocation = lastMark;

-	        } else {

-	            return null;

-	        }

-	    }

-	    

-	    try {

-	        while(true) {

-	            LogRecord record = logger.get(null, toLong(lastLocation));

-		        // I assume getNext will return null if there is no next record. 

-	            LogRecord next = logger.getNext(record);

-	            if( next==null || next.length == 0 )

-	                return null;

-	            lastLocation = new LongRecordLocation(next.key);

-	            if( !next.isCTRL() )

-	                return lastLocation;

-	        }

-		} catch (Exception e) {

-			throw (InvalidRecordLocationException)new InvalidRecordLocationException().initCause(e);

-        }

-		

-	}

-

-	/**

-	 * @see org.apache.activeio.journal.Journal#read(org.codehaus.activemq.journal.RecordLocation)

-	 */

-	public Packet read(RecordLocation location)

-			throws InvalidRecordLocationException, IOException {

-	    

-	    try {

-            LogRecord record = logger.get(null, toLong(location));

-            return new ByteArrayPacket(record.data);            

-		} catch (InvalidLogKeyException e) {

-			throw new InvalidRecordLocationException(e.getMessage(), e);

-		} catch (Exception e) {

-			throw (IOException) new IOException("Journal write failed: " + e)

-					.initCause(e);

-		}

-		

-	}

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.howl;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+
+import org.apache.activeio.journal.InvalidRecordLocationException;
+import org.apache.activeio.journal.Journal;
+import org.apache.activeio.journal.JournalEventListener;
+import org.apache.activeio.journal.RecordLocation;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+import org.objectweb.howl.log.Configuration;
+import org.objectweb.howl.log.InvalidFileSetException;
+import org.objectweb.howl.log.InvalidLogBufferException;
+import org.objectweb.howl.log.InvalidLogKeyException;
+import org.objectweb.howl.log.LogConfigurationException;
+import org.objectweb.howl.log.LogEventListener;
+import org.objectweb.howl.log.LogRecord;
+import org.objectweb.howl.log.Logger;
+
+/**
+ * An implementation of the Journal interface using a HOWL logger.  This is is a thin
+ * wrapper around a HOWL logger.
+ * 
+ * This implementation can be used to write records but not to retreive them
+ * yet. Once the HOWL logger implements the methods needed to retreive
+ * previously stored records, this class can be completed.
+ * 
+ * @version $Revision: 1.2 $
+ */
+public class HowlJournal implements Journal {
+
+	private final Logger logger;
+
+	private RecordLocation lastMark;
+
+	public HowlJournal(Configuration configuration)
+			throws InvalidFileSetException, LogConfigurationException,
+			InvalidLogBufferException, ClassNotFoundException, IOException,
+			InterruptedException {
+		this.logger = new Logger(configuration);
+		this.logger.open();
+		lastMark = new LongRecordLocation(logger.getActiveMark());
+	}
+
+	/**
+	 * @see org.apache.activeio.journal.Journal#write(byte[], boolean)
+	 */
+	public RecordLocation write(Packet packet, boolean sync) throws IOException {
+		try {
+			return new LongRecordLocation(logger.put(packet.sliceAsBytes(), sync));
+		} catch (InterruptedException e) {
+			throw (InterruptedIOException) new InterruptedIOException()
+					.initCause(e);
+		} catch (IOException e) {
+			throw e;
+		} catch (Exception e) {
+			throw (IOException) new IOException("Journal write failed: " + e)
+					.initCause(e);
+		}
+	}
+
+	/**
+	 * @see org.apache.activeio.journal.Journal#setMark(org.codehaus.activemq.journal.RecordLocation, boolean)
+	 */
+	public void setMark(RecordLocation recordLocator, boolean force)
+			throws InvalidRecordLocationException, IOException {
+		try {
+			long location = toLong(recordLocator);
+			logger.mark(location, force);
+			lastMark = recordLocator;
+
+		} catch (InterruptedException e) {
+			throw (InterruptedIOException) new InterruptedIOException()
+					.initCause(e);
+		} catch (IOException e) {
+			throw e;
+		} catch (InvalidLogKeyException e) {
+			throw new InvalidRecordLocationException(e.getMessage(), e);
+		} catch (Exception e) {
+			throw (IOException) new IOException("Journal write failed: " + e)
+					.initCause(e);
+		}
+	}
+	
+	/**
+     * @param recordLocator
+     * @return
+     * @throws InvalidRecordLocationException
+     */
+    private long toLong(RecordLocation recordLocator) throws InvalidRecordLocationException {
+        if (recordLocator == null
+        		|| recordLocator.getClass() != LongRecordLocation.class)
+        	throw new InvalidRecordLocationException();
+
+        long location = ((LongRecordLocation) recordLocator)
+        		.getLongLocation();
+        return location;
+    }
+
+    /**
+	 * @see org.apache.activeio.journal.Journal#getMark()
+	 */
+	public RecordLocation getMark() {
+		return lastMark;
+	}
+
+	/**
+	 * @see org.apache.activeio.journal.Journal#close()
+	 */
+	public void close() throws IOException {
+		try {
+			logger.close();
+		} catch (IOException e) {
+			throw e;
+		} catch (InterruptedException e) {
+			throw (InterruptedIOException) new InterruptedIOException()
+					.initCause(e);
+		} catch (Exception e) {
+			throw (IOException) new IOException("Journal close failed: " + e)
+					.initCause(e);
+		}
+	}
+
+	/**
+	 * @see org.apache.activeio.journal.Journal#setJournalEventListener(org.codehaus.activemq.journal.JournalEventListener)
+	 */
+	public void setJournalEventListener(final JournalEventListener eventListener) {
+		logger.setLogEventListener(new LogEventListener() {
+			public void logOverflowNotification(long key) {
+				eventListener.overflowNotification(new LongRecordLocation(key));
+			}
+		});
+	}
+
+	/**
+	 * @see org.apache.activeio.journal.Journal#getNextRecordLocation(org.codehaus.activemq.journal.RecordLocation)
+	 */
+	public RecordLocation getNextRecordLocation(RecordLocation lastLocation)
+			throws InvalidRecordLocationException {
+	    
+	    if( lastLocation ==null ) {
+	        if( this.lastMark !=null ) {
+	            lastLocation = lastMark;
+	        } else {
+	            return null;
+	        }
+	    }
+	    
+	    try {
+	        while(true) {
+	            LogRecord record = logger.get(null, toLong(lastLocation));
+		        // I assume getNext will return null if there is no next record. 
+	            LogRecord next = logger.getNext(record);
+	            if( next==null || next.length == 0 )
+	                return null;
+	            lastLocation = new LongRecordLocation(next.key);
+	            if( !next.isCTRL() )
+	                return lastLocation;
+	        }
+		} catch (Exception e) {
+			throw (InvalidRecordLocationException)new InvalidRecordLocationException().initCause(e);
+        }
+		
+	}
+
+	/**
+	 * @see org.apache.activeio.journal.Journal#read(org.codehaus.activemq.journal.RecordLocation)
+	 */
+	public Packet read(RecordLocation location)
+			throws InvalidRecordLocationException, IOException {
+	    
+	    try {
+            LogRecord record = logger.get(null, toLong(location));
+            return new ByteArrayPacket(record.data);            
+		} catch (InvalidLogKeyException e) {
+			throw new InvalidRecordLocationException(e.getMessage(), e);
+		} catch (Exception e) {
+			throw (IOException) new IOException("Journal write failed: " + e)
+					.initCause(e);
+		}
+		
+	}
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/journal/howl/LongRecordLocation.java b/activeio-core/src/main/java/org/apache/activeio/journal/howl/LongRecordLocation.java
index 972bd42..05474ba 100644
--- a/activeio-core/src/main/java/org/apache/activeio/journal/howl/LongRecordLocation.java
+++ b/activeio-core/src/main/java/org/apache/activeio/journal/howl/LongRecordLocation.java
@@ -1,73 +1,73 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.howl;

-

-import org.apache.activeio.journal.RecordLocation;

-

-/**

- * Provides a RecordLocation implementation for the long based

- * location pointers that HOWL uses.

- * 

- * @version $Revision: 1.1 $

- */

-public class LongRecordLocation implements RecordLocation {

-

-	final private long location;

-

-	public LongRecordLocation(long l) {

-		this.location = l;

-	}

-

-	/**

-	 * @see java.lang.Comparable#compareTo(java.lang.Object)

-	 */

-	public int compareTo(Object o) {

-		return (int) (location - ((LongRecordLocation) o).location);

-	}

-

-	/**

-	 * @return the original long location provided by HOWL

-	 */

-	public long getLongLocation() {

-		return location;

-	}

-

-	/**

-	 * @see java.lang.Object#hashCode()

-	 */

-	public int hashCode() {

-		int lowPart = (int) (0xFFFFFFFF & location);

-		int highPart = (int) (0xFFFFFFFF & (location >> 4));

-		return lowPart ^ highPart;

-	}

-

-	/**

-	 * @see java.lang.Object#equals(java.lang.Object)

-	 */

-	public boolean equals(Object o) {

-		if (o == null || o.getClass() != LongRecordLocation.class)

-			return false;

-		return ((LongRecordLocation) o).location == location;

-	}

-

-	/**

-	 * @see java.lang.Object#toString()

-	 */

-	public String toString() {

-		return "0x" + Long.toHexString(location);

-	}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.howl;
+
+import org.apache.activeio.journal.RecordLocation;
+
+/**
+ * Provides a RecordLocation implementation for the long based
+ * location pointers that HOWL uses.
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class LongRecordLocation implements RecordLocation {
+
+	final private long location;
+
+	public LongRecordLocation(long l) {
+		this.location = l;
+	}
+
+	/**
+	 * @see java.lang.Comparable#compareTo(java.lang.Object)
+	 */
+	public int compareTo(Object o) {
+		return (int) (location - ((LongRecordLocation) o).location);
+	}
+
+	/**
+	 * @return the original long location provided by HOWL
+	 */
+	public long getLongLocation() {
+		return location;
+	}
+
+	/**
+	 * @see java.lang.Object#hashCode()
+	 */
+	public int hashCode() {
+		int lowPart = (int) (0xFFFFFFFF & location);
+		int highPart = (int) (0xFFFFFFFF & (location >> 4));
+		return lowPart ^ highPart;
+	}
+
+	/**
+	 * @see java.lang.Object#equals(java.lang.Object)
+	 */
+	public boolean equals(Object o) {
+		if (o == null || o.getClass() != LongRecordLocation.class)
+			return false;
+		return ((LongRecordLocation) o).location == location;
+	}
+
+	/**
+	 * @see java.lang.Object#toString()
+	 */
+	public String toString() {
+		return "0x" + Long.toHexString(location);
+	}
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java b/activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java
index 15225f0..25eca6d 100644
--- a/activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/oneport/HttpRecognizer.java
@@ -1,66 +1,66 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport;

-

-import java.util.HashSet;

-

-import org.apache.activeio.packet.Packet;

-

-

-public class HttpRecognizer implements ProtocolRecognizer {

-

-    static private HashSet methods = new HashSet();

-    static {

-        // This list built using: http://www.w3.org/Protocols/HTTP/Methods.html

-        methods.add("GET ");

-        methods.add("PUT ");

-        methods.add("POST ");

-        methods.add("HEAD ");

-        methods.add("LINK ");

-        methods.add("TRACE ");

-        methods.add("UNLINK ");

-        methods.add("SEARCH ");

-        methods.add("DELETE ");

-        methods.add("CHECKIN ");

-        methods.add("OPTIONS ");

-        methods.add("CONNECT ");

-        methods.add("CHECKOUT ");

-        methods.add("SPACEJUMP ");

-        methods.add("SHOWMETHOD ");

-        methods.add("TEXTSEARCH ");        

-    }

-    

-    static final public HttpRecognizer HTTP_RECOGNIZER = new HttpRecognizer();

-    

-    private HttpRecognizer() {}

-    

-    public boolean recognizes(Packet packet) {

-        

-        StringBuffer b = new StringBuffer(12);

-        for (int i = 0; i < 11; i++) {

-            int c = (char)packet.read();

-            if( c == -1)

-                return false;

-            

-            b.append((char)c);

-            if(((char)c)==' ')

-                break;

-        }

-        

-        return methods.contains(b.toString());

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport;
+
+import java.util.HashSet;
+
+import org.apache.activeio.packet.Packet;
+
+
+public class HttpRecognizer implements ProtocolRecognizer {
+
+    static private HashSet methods = new HashSet();
+    static {
+        // This list built using: http://www.w3.org/Protocols/HTTP/Methods.html
+        methods.add("GET ");
+        methods.add("PUT ");
+        methods.add("POST ");
+        methods.add("HEAD ");
+        methods.add("LINK ");
+        methods.add("TRACE ");
+        methods.add("UNLINK ");
+        methods.add("SEARCH ");
+        methods.add("DELETE ");
+        methods.add("CHECKIN ");
+        methods.add("OPTIONS ");
+        methods.add("CONNECT ");
+        methods.add("CHECKOUT ");
+        methods.add("SPACEJUMP ");
+        methods.add("SHOWMETHOD ");
+        methods.add("TEXTSEARCH ");        
+    }
+    
+    static final public HttpRecognizer HTTP_RECOGNIZER = new HttpRecognizer();
+    
+    private HttpRecognizer() {}
+    
+    public boolean recognizes(Packet packet) {
+        
+        StringBuffer b = new StringBuffer(12);
+        for (int i = 0; i < 11; i++) {
+            int c = (char)packet.read();
+            if( c == -1)
+                return false;
+            
+            b.append((char)c);
+            if(((char)c)==' ')
+                break;
+        }
+        
+        return methods.contains(b.toString());
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/oneport/IIOPRecognizer.java b/activeio-core/src/main/java/org/apache/activeio/oneport/IIOPRecognizer.java
index 1eb6935..78b8b38 100644
--- a/activeio-core/src/main/java/org/apache/activeio/oneport/IIOPRecognizer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/oneport/IIOPRecognizer.java
@@ -1,36 +1,36 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport;

-

-import org.apache.activeio.packet.Packet;

-

-

-public class IIOPRecognizer implements ProtocolRecognizer {

-    

-    static final public IIOPRecognizer IIOP_RECOGNIZER = new IIOPRecognizer();

-    

-    private IIOPRecognizer() {}

-    

-    public boolean recognizes(Packet packet) {

-        return ( 

-            packet.read()=='G' &&

-            packet.read()=='I' &&

-            packet.read()=='O' &&

-            packet.read()=='P' 

-                );

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport;
+
+import org.apache.activeio.packet.Packet;
+
+
+public class IIOPRecognizer implements ProtocolRecognizer {
+    
+    static final public IIOPRecognizer IIOP_RECOGNIZER = new IIOPRecognizer();
+    
+    private IIOPRecognizer() {}
+    
+    public boolean recognizes(Packet packet) {
+        return ( 
+            packet.read()=='G' &&
+            packet.read()=='I' &&
+            packet.read()=='O' &&
+            packet.read()=='P' 
+                );
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/oneport/OnePortAsyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/oneport/OnePortAsyncChannelServer.java
index 8407649..493a7d5 100644
--- a/activeio-core/src/main/java/org/apache/activeio/oneport/OnePortAsyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/oneport/OnePortAsyncChannelServer.java
@@ -1,223 +1,223 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport;

-

-import java.io.IOException;

-import java.net.URI;

-import java.util.Iterator;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.Channel;

-import org.apache.activeio.adapter.AsyncToSyncChannel;

-import org.apache.activeio.adapter.SyncToAsyncChannel;

-import org.apache.activeio.packet.AppendedPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelListener;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.async.FilterAsyncChannel;

-import org.apache.activeio.packet.async.FilterAsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.filter.PushbackSyncChannel;

-

-import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;

-

-/**

- * Allows multiple protocols share a single ChannelServer.  All protocols sharing the server 

- * must have a distinct magic number at the beginning of the client's request.

- * 

- * TODO: handle the case where a client opens a connection but sends no data down the stream.  We need

- * to timeout that client.

- * 

- * @version $Revision$

- */

-final public class OnePortAsyncChannelServer extends FilterAsyncChannelServer {

-    

-    /**

-     * The OnePortAsyncChannelServer listens for incoming connection

-     * from a normal AsyncChannelServer.  This s the listner used 

-     * to receive the accepted channels.

-     */

-    final private class OnePortAcceptListener implements AcceptListener {

-        

-        public void onAccept(Channel channel) {

-            try {

-                AsyncChannel asyncChannel = SyncToAsyncChannel.adapt(channel);

-                ProtocolInspectingAsyncChannel inspector = new ProtocolInspectingAsyncChannel(asyncChannel);

-                inspector.start();                

-            } catch (IOException e) {

-                onAcceptError(e);

-            }                

-        }

-        

-        public void onAcceptError(IOException error) {

-            dispose();

-        }

-    }

-

-    /**

-     * This channel filter sniffs the first few bytes of the byte stream 

-     * to see if a ProtocolRecognizer recognizes the protocol.  If it does not

-     * it just closes the channel, otherwise the associated SubPortAsyncChannelServer

-     * is notified that it accepted a channel.

-     *

-     */

-    final private class ProtocolInspectingAsyncChannel extends FilterAsyncChannel {

-        private Packet buffer;

-

-        public ProtocolInspectingAsyncChannel(AsyncChannel next) throws IOException {

-            super(next);

-            setAsyncChannelListener(new AsyncChannelListener() {

-                public void onPacket(Packet packet) {

-                    if (buffer == null) {

-                        buffer = packet;

-                    } else {

-                        buffer = AppendedPacket.join(buffer, packet);

-                    }

-                    findMagicNumber();

-                }

-

-                public void onPacketError(IOException error) {

-                    dispose();

-                }

-            });

-        }

-

-        private void findMagicNumber() {

-            for (Iterator iter = recognizerMap.keySet().iterator(); iter.hasNext();) {

-                ProtocolRecognizer recognizer = (ProtocolRecognizer) iter.next();

-                if (recognizer.recognizes(buffer.duplicate())) {

-

-                    if( UnknownRecognizer.UNKNOWN_RECOGNIZER == recognizer ) {

-                        // Dispose the channel.. don't know what to do with it.

-                        dispose();

-                    }

-                    

-                    SubPortAsyncChannelServer onePort = (SubPortAsyncChannelServer) recognizerMap.get(recognizer);

-                    if( onePort == null ) {

-                        // Dispose the channel.. don't know what to do with it.

-                        dispose();

-                    }

-

-                    // Once the magic number is found:

-                    // Stop the channel so that a decision can be taken on what to

-                    // do with the

-                    // channel. When the channel is restarted, the buffered up

-                    // packets wiil get

-                    // delivered.

-                    try {

-                        stop();

-                        setAsyncChannelListener(null);

-                    } catch (IOException e) {                        

-                        getAsyncChannelListener().onPacketError(e);

-                    }

-                    

-                    Channel channel = getNext();

-                    channel = AsyncToSyncChannel.adapt(channel);

-                    channel = new PushbackSyncChannel((SyncChannel) channel, buffer);

-                    channel = SyncToAsyncChannel.adapt(channel);

-                    

-                    onePort.onAccept(channel);

-                    break;

-                }

-            }

-        }

-    }    

-

-    /**

-     * Clients bind against the OnePortAsyncChannelServer and get 

-     * SubPortAsyncChannelServer which can be used to accept connections.

-     */

-    final private class SubPortAsyncChannelServer implements AsyncChannelServer {

-        

-        private final ProtocolRecognizer recognizer;

-        private AcceptListener acceptListener;

-        private boolean started;

-        

-        /**

-         * @param recognizer

-         */

-        public SubPortAsyncChannelServer(ProtocolRecognizer recognizer) {

-            this.recognizer = recognizer;

-        }

-

-        public void setAcceptListener(AcceptListener acceptListener) {

-            this.acceptListener = acceptListener;

-        }

-        

-        public URI getBindURI() {

-            return next.getBindURI();

-        }

-        

-        public URI getConnectURI() {

-            return next.getConnectURI();

-        }

-        

-        public void dispose() {

-            started = false;

-            recognizerMap.remove(recognizer);

-        }

-        

-        public void start() throws IOException {

-            started = true;

-        }

-        public void stop() throws IOException {

-            started = false;

-        }

-        

-        void onAccept(Channel channel) {

-            if( started && acceptListener!=null ) {

-                acceptListener.onAccept(channel);

-            } else {

-                // Dispose the channel.. don't know what to do with it.

-                channel.dispose();

-            }

-        }

-        

-        public Object getAdapter(Class target) {

-            if( target.isAssignableFrom(getClass()) ) {

-                return this;

-            }

-            return OnePortAsyncChannelServer.this.getAdapter(target);

-        }    

-        

-    }

-    

-    

-    private final ConcurrentHashMap recognizerMap = new ConcurrentHashMap();

-

-    public OnePortAsyncChannelServer(AsyncChannelServer server) throws IOException {

-        super(server);

-        super.setAcceptListener(new OnePortAcceptListener());

-    }

-    

-    public void setAcceptListener(AcceptListener acceptListener) {

-        throw new IllegalAccessError("Not supported");

-    }    

-    

-    public AsyncChannelServer bindAsyncChannel(ProtocolRecognizer recognizer) throws IOException {

-        

-        if( recognizerMap.contains(recognizer) ) 

-            throw new IOException("That recognizer is allredy bound.");

-        

-        SubPortAsyncChannelServer server = new SubPortAsyncChannelServer(recognizer);

-        Object old = recognizerMap.put(recognizer, server);

-        return server;

-    }

-    

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.Iterator;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.Channel;
+import org.apache.activeio.adapter.AsyncToSyncChannel;
+import org.apache.activeio.adapter.SyncToAsyncChannel;
+import org.apache.activeio.packet.AppendedPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelListener;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.async.FilterAsyncChannel;
+import org.apache.activeio.packet.async.FilterAsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.filter.PushbackSyncChannel;
+
+import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Allows multiple protocols share a single ChannelServer.  All protocols sharing the server 
+ * must have a distinct magic number at the beginning of the client's request.
+ * 
+ * TODO: handle the case where a client opens a connection but sends no data down the stream.  We need
+ * to timeout that client.
+ * 
+ * @version $Revision$
+ */
+final public class OnePortAsyncChannelServer extends FilterAsyncChannelServer {
+    
+    /**
+     * The OnePortAsyncChannelServer listens for incoming connection
+     * from a normal AsyncChannelServer.  This s the listner used 
+     * to receive the accepted channels.
+     */
+    final private class OnePortAcceptListener implements AcceptListener {
+        
+        public void onAccept(Channel channel) {
+            try {
+                AsyncChannel asyncChannel = SyncToAsyncChannel.adapt(channel);
+                ProtocolInspectingAsyncChannel inspector = new ProtocolInspectingAsyncChannel(asyncChannel);
+                inspector.start();                
+            } catch (IOException e) {
+                onAcceptError(e);
+            }                
+        }
+        
+        public void onAcceptError(IOException error) {
+            dispose();
+        }
+    }
+
+    /**
+     * This channel filter sniffs the first few bytes of the byte stream 
+     * to see if a ProtocolRecognizer recognizes the protocol.  If it does not
+     * it just closes the channel, otherwise the associated SubPortAsyncChannelServer
+     * is notified that it accepted a channel.
+     *
+     */
+    final private class ProtocolInspectingAsyncChannel extends FilterAsyncChannel {
+        private Packet buffer;
+
+        public ProtocolInspectingAsyncChannel(AsyncChannel next) throws IOException {
+            super(next);
+            setAsyncChannelListener(new AsyncChannelListener() {
+                public void onPacket(Packet packet) {
+                    if (buffer == null) {
+                        buffer = packet;
+                    } else {
+                        buffer = AppendedPacket.join(buffer, packet);
+                    }
+                    findMagicNumber();
+                }
+
+                public void onPacketError(IOException error) {
+                    dispose();
+                }
+            });
+        }
+
+        private void findMagicNumber() {
+            for (Iterator iter = recognizerMap.keySet().iterator(); iter.hasNext();) {
+                ProtocolRecognizer recognizer = (ProtocolRecognizer) iter.next();
+                if (recognizer.recognizes(buffer.duplicate())) {
+
+                    if( UnknownRecognizer.UNKNOWN_RECOGNIZER == recognizer ) {
+                        // Dispose the channel.. don't know what to do with it.
+                        dispose();
+                    }
+                    
+                    SubPortAsyncChannelServer onePort = (SubPortAsyncChannelServer) recognizerMap.get(recognizer);
+                    if( onePort == null ) {
+                        // Dispose the channel.. don't know what to do with it.
+                        dispose();
+                    }
+
+                    // Once the magic number is found:
+                    // Stop the channel so that a decision can be taken on what to
+                    // do with the
+                    // channel. When the channel is restarted, the buffered up
+                    // packets wiil get
+                    // delivered.
+                    try {
+                        stop();
+                        setAsyncChannelListener(null);
+                    } catch (IOException e) {                        
+                        getAsyncChannelListener().onPacketError(e);
+                    }
+                    
+                    Channel channel = getNext();
+                    channel = AsyncToSyncChannel.adapt(channel);
+                    channel = new PushbackSyncChannel((SyncChannel) channel, buffer);
+                    channel = SyncToAsyncChannel.adapt(channel);
+                    
+                    onePort.onAccept(channel);
+                    break;
+                }
+            }
+        }
+    }    
+
+    /**
+     * Clients bind against the OnePortAsyncChannelServer and get 
+     * SubPortAsyncChannelServer which can be used to accept connections.
+     */
+    final private class SubPortAsyncChannelServer implements AsyncChannelServer {
+        
+        private final ProtocolRecognizer recognizer;
+        private AcceptListener acceptListener;
+        private boolean started;
+        
+        /**
+         * @param recognizer
+         */
+        public SubPortAsyncChannelServer(ProtocolRecognizer recognizer) {
+            this.recognizer = recognizer;
+        }
+
+        public void setAcceptListener(AcceptListener acceptListener) {
+            this.acceptListener = acceptListener;
+        }
+        
+        public URI getBindURI() {
+            return next.getBindURI();
+        }
+        
+        public URI getConnectURI() {
+            return next.getConnectURI();
+        }
+        
+        public void dispose() {
+            started = false;
+            recognizerMap.remove(recognizer);
+        }
+        
+        public void start() throws IOException {
+            started = true;
+        }
+        public void stop() throws IOException {
+            started = false;
+        }
+        
+        void onAccept(Channel channel) {
+            if( started && acceptListener!=null ) {
+                acceptListener.onAccept(channel);
+            } else {
+                // Dispose the channel.. don't know what to do with it.
+                channel.dispose();
+            }
+        }
+        
+        public Object getAdapter(Class target) {
+            if( target.isAssignableFrom(getClass()) ) {
+                return this;
+            }
+            return OnePortAsyncChannelServer.this.getAdapter(target);
+        }    
+        
+    }
+    
+    
+    private final ConcurrentHashMap recognizerMap = new ConcurrentHashMap();
+
+    public OnePortAsyncChannelServer(AsyncChannelServer server) throws IOException {
+        super(server);
+        super.setAcceptListener(new OnePortAcceptListener());
+    }
+    
+    public void setAcceptListener(AcceptListener acceptListener) {
+        throw new IllegalAccessError("Not supported");
+    }    
+    
+    public AsyncChannelServer bindAsyncChannel(ProtocolRecognizer recognizer) throws IOException {
+        
+        if( recognizerMap.contains(recognizer) ) 
+            throw new IOException("That recognizer is allredy bound.");
+        
+        SubPortAsyncChannelServer server = new SubPortAsyncChannelServer(recognizer);
+        Object old = recognizerMap.put(recognizer, server);
+        return server;
+    }
+    
+    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/oneport/ProtocolRecognizer.java b/activeio-core/src/main/java/org/apache/activeio/oneport/ProtocolRecognizer.java
index 51a8a8b..f30bf2e 100644
--- a/activeio-core/src/main/java/org/apache/activeio/oneport/ProtocolRecognizer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/oneport/ProtocolRecognizer.java
@@ -1,26 +1,26 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport;

-

-import org.apache.activeio.packet.Packet;

-

-/**

- *

- */

-public interface ProtocolRecognizer {

-    boolean recognizes(Packet packet);

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport;
+
+import org.apache.activeio.packet.Packet;
+
+/**
+ *
+ */
+public interface ProtocolRecognizer {
+    boolean recognizes(Packet packet);
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/oneport/UnknownRecognizer.java b/activeio-core/src/main/java/org/apache/activeio/oneport/UnknownRecognizer.java
index eaa51ab..af58183 100644
--- a/activeio-core/src/main/java/org/apache/activeio/oneport/UnknownRecognizer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/oneport/UnknownRecognizer.java
@@ -1,34 +1,34 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport;

-

-import org.apache.activeio.packet.Packet;

-

-

-class UnknownRecognizer implements ProtocolRecognizer {

-    

-    static public final ProtocolRecognizer UNKNOWN_RECOGNIZER = new UnknownRecognizer();

-    

-    private UnknownRecognizer() {        

-    }

-    

-    public boolean recognizes(Packet packet) {

-        if( packet.limit() > 15 )

-            return true;

-        return false;

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport;
+
+import org.apache.activeio.packet.Packet;
+
+
+class UnknownRecognizer implements ProtocolRecognizer {
+    
+    static public final ProtocolRecognizer UNKNOWN_RECOGNIZER = new UnknownRecognizer();
+    
+    private UnknownRecognizer() {        
+    }
+    
+    public boolean recognizes(Packet packet) {
+        if( packet.limit() > 15 )
+            return true;
+        return false;
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/AppendedPacket.java b/activeio-core/src/main/java/org/apache/activeio/packet/AppendedPacket.java
index 381151d..9de5e3a 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/AppendedPacket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/AppendedPacket.java
@@ -1,245 +1,245 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-import java.lang.reflect.Constructor;

-

-

-/**

- * Appends two packets together.

- * 

- * @version $Revision$

- */

-final public class AppendedPacket implements Packet {

-

-    private final Packet first;

-    private final Packet last;

-

-    private final int capacity;

-    private final int firstCapacity;

-

-    static public Packet join(Packet first, Packet last) {

-        if( first.hasRemaining() ) {

-            if( last.hasRemaining() ) {

-                

-                //TODO: this might even be a rejoin of the same continous buffer.

-                //It would be good if we detected that and avoided just returned the buffer.

-                

-                return new AppendedPacket(first.slice(), last.slice());               

-            } else {

-                return first.slice();

-            }

-        } else {

-            if( last.hasRemaining() ) {

-                return last.slice();                

-            } else {

-                return EmptyPacket.EMPTY_PACKET;

-            }            

-        }

-    }

-    

-    /**

-     * @deprecated use {@see #join(Packet, Packet)} instead.

-     */

-    public AppendedPacket(Packet first, Packet second) {

-        this.first = first;

-        this.last = second;

-        this.firstCapacity = first.capacity();

-        this.capacity = first.capacity()+last.capacity();

-        clear();        

-    }

-        

-    public void position(int position) {

-        if( position <= firstCapacity ) {

-            last.position(0);

-            first.position(position);

-        } else {

-            last.position(position-firstCapacity);

-            first.position(firstCapacity);

-        }

-    }

-    

-    public void limit(int limit) {

-        if( limit <= firstCapacity ) {

-            last.limit(0);

-            first.limit(limit);

-        } else {

-            last.limit(limit-firstCapacity);

-            first.limit(firstCapacity);

-        }

-    }

-

-    public Packet slice() {

-        return join(first,last);

-    }

-

-    public Packet duplicate() {

-        return new AppendedPacket(first.duplicate(), last.duplicate());               

-    }

-

-    public Object duplicate(ClassLoader cl) throws IOException {

-        try {

-            Class pclazz = cl.loadClass(Packet.class.getName());

-            Class clazz = cl.loadClass(AppendedPacket.class.getName());

-            Constructor constructor = clazz.getConstructor(new Class[]{pclazz, pclazz});

-            return constructor.newInstance(new Object[]{first.duplicate(cl), last.duplicate(cl)});

-        } catch (Throwable e) {

-            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);

-        }

-    }

-    

-    public void flip() {

-        limit(position());

-        position(0);

-    }

-

-    public int position() {

-        return first.position()+last.position();

-    }

-    

-    public int limit() {

-        return first.limit()+last.limit();

-    }    

-

-    public int remaining() {

-        return first.remaining()+last.remaining();

-    }

-

-    public void rewind() {

-        first.rewind();

-        last.rewind();

-    }

-

-    public boolean hasRemaining() {

-        return first.hasRemaining()||last.hasRemaining();

-    }

-

-    public void clear() {

-        first.clear();

-        last.clear();        

-    }

-

-    public int capacity() {

-        return capacity;

-    }

-

-    public void writeTo(OutputStream out) throws IOException {

-        first.writeTo(out);

-        last.writeTo(out);

-    }

-    

-    public void writeTo(DataOutput out) throws IOException {

-        first.writeTo(out);

-        last.writeTo(out);

-    }

-

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read()

-     */

-    public int read() {

-        if( first.hasRemaining() ) {

-            return first.read();

-        } else if( last.hasRemaining() ) {

-            return last.read();

-        } else {

-            return -1;

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)

-     */

-    public int read(byte[] data, int offset, int length) {        

-        

-        int rc1 = first.read(data, offset, length);        

-        if( rc1==-1 ) {

-            int rc2 = last.read(data, offset, length);

-            return ( rc2==-1 ) ? -1 : rc2;

-        } else {

-            int rc2 = last.read(data, offset+rc1, length-rc1);

-            return ( rc2==-1 ) ? rc1 : rc1+rc2;

-        }

-

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(int)

-     */

-    public boolean write(int data) {

-        if( first.hasRemaining() ) {

-            return first.write(data);

-        } else if( last.hasRemaining() ) {

-            return last.write(data);

-        } else {

-            return false;

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)

-     */

-    public int write(byte[] data, int offset, int length) {

-        int rc1 = first.write(data, offset, length);        

-        if( rc1==-1 ) {

-            int rc2 = last.write(data, offset, length);

-            return ( rc2==-1 ) ? -1 : rc2;

-        } else {

-            int rc2 = last.write(data, offset+rc1, length-rc1);

-            return ( rc2==-1 ) ? rc1 : rc1+rc2;

-        }

-    }

-

-    public int read(Packet dest) {        

-	    int rc = first.read(dest);

-	    rc += last.read(dest);

-	    return rc;

-    }    

-    

-    public String toString() {

-        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        Object object = first.getAdapter(target);

-        if( object == null )

-            object = last.getAdapter(target);

-        return object;

-    }

-

-    public ByteSequence asByteSequence() {      

-        // TODO: implement me

-        return null;

-    }

-

-    public byte[] sliceAsBytes() {

-        // TODO: implement me

-        return null;

-    }

-

-    public void dispose() {

-        first.dispose();

-        last.dispose();

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+
+
+/**
+ * Appends two packets together.
+ * 
+ * @version $Revision$
+ */
+final public class AppendedPacket implements Packet {
+
+    private final Packet first;
+    private final Packet last;
+
+    private final int capacity;
+    private final int firstCapacity;
+
+    static public Packet join(Packet first, Packet last) {
+        if( first.hasRemaining() ) {
+            if( last.hasRemaining() ) {
+                
+                //TODO: this might even be a rejoin of the same continous buffer.
+                //It would be good if we detected that and avoided just returned the buffer.
+                
+                return new AppendedPacket(first.slice(), last.slice());               
+            } else {
+                return first.slice();
+            }
+        } else {
+            if( last.hasRemaining() ) {
+                return last.slice();                
+            } else {
+                return EmptyPacket.EMPTY_PACKET;
+            }            
+        }
+    }
+    
+    /**
+     * @deprecated use {@see #join(Packet, Packet)} instead.
+     */
+    public AppendedPacket(Packet first, Packet second) {
+        this.first = first;
+        this.last = second;
+        this.firstCapacity = first.capacity();
+        this.capacity = first.capacity()+last.capacity();
+        clear();        
+    }
+        
+    public void position(int position) {
+        if( position <= firstCapacity ) {
+            last.position(0);
+            first.position(position);
+        } else {
+            last.position(position-firstCapacity);
+            first.position(firstCapacity);
+        }
+    }
+    
+    public void limit(int limit) {
+        if( limit <= firstCapacity ) {
+            last.limit(0);
+            first.limit(limit);
+        } else {
+            last.limit(limit-firstCapacity);
+            first.limit(firstCapacity);
+        }
+    }
+
+    public Packet slice() {
+        return join(first,last);
+    }
+
+    public Packet duplicate() {
+        return new AppendedPacket(first.duplicate(), last.duplicate());               
+    }
+
+    public Object duplicate(ClassLoader cl) throws IOException {
+        try {
+            Class pclazz = cl.loadClass(Packet.class.getName());
+            Class clazz = cl.loadClass(AppendedPacket.class.getName());
+            Constructor constructor = clazz.getConstructor(new Class[]{pclazz, pclazz});
+            return constructor.newInstance(new Object[]{first.duplicate(cl), last.duplicate(cl)});
+        } catch (Throwable e) {
+            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);
+        }
+    }
+    
+    public void flip() {
+        limit(position());
+        position(0);
+    }
+
+    public int position() {
+        return first.position()+last.position();
+    }
+    
+    public int limit() {
+        return first.limit()+last.limit();
+    }    
+
+    public int remaining() {
+        return first.remaining()+last.remaining();
+    }
+
+    public void rewind() {
+        first.rewind();
+        last.rewind();
+    }
+
+    public boolean hasRemaining() {
+        return first.hasRemaining()||last.hasRemaining();
+    }
+
+    public void clear() {
+        first.clear();
+        last.clear();        
+    }
+
+    public int capacity() {
+        return capacity;
+    }
+
+    public void writeTo(OutputStream out) throws IOException {
+        first.writeTo(out);
+        last.writeTo(out);
+    }
+    
+    public void writeTo(DataOutput out) throws IOException {
+        first.writeTo(out);
+        last.writeTo(out);
+    }
+
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read()
+     */
+    public int read() {
+        if( first.hasRemaining() ) {
+            return first.read();
+        } else if( last.hasRemaining() ) {
+            return last.read();
+        } else {
+            return -1;
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)
+     */
+    public int read(byte[] data, int offset, int length) {        
+        
+        int rc1 = first.read(data, offset, length);        
+        if( rc1==-1 ) {
+            int rc2 = last.read(data, offset, length);
+            return ( rc2==-1 ) ? -1 : rc2;
+        } else {
+            int rc2 = last.read(data, offset+rc1, length-rc1);
+            return ( rc2==-1 ) ? rc1 : rc1+rc2;
+        }
+
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(int)
+     */
+    public boolean write(int data) {
+        if( first.hasRemaining() ) {
+            return first.write(data);
+        } else if( last.hasRemaining() ) {
+            return last.write(data);
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)
+     */
+    public int write(byte[] data, int offset, int length) {
+        int rc1 = first.write(data, offset, length);        
+        if( rc1==-1 ) {
+            int rc2 = last.write(data, offset, length);
+            return ( rc2==-1 ) ? -1 : rc2;
+        } else {
+            int rc2 = last.write(data, offset+rc1, length-rc1);
+            return ( rc2==-1 ) ? rc1 : rc1+rc2;
+        }
+    }
+
+    public int read(Packet dest) {        
+	    int rc = first.read(dest);
+	    rc += last.read(dest);
+	    return rc;
+    }    
+    
+    public String toString() {
+        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        Object object = first.getAdapter(target);
+        if( object == null )
+            object = last.getAdapter(target);
+        return object;
+    }
+
+    public ByteSequence asByteSequence() {      
+        // TODO: implement me
+        return null;
+    }
+
+    public byte[] sliceAsBytes() {
+        // TODO: implement me
+        return null;
+    }
+
+    public void dispose() {
+        first.dispose();
+        last.dispose();
+    }
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/ByteArrayPacket.java b/activeio-core/src/main/java/org/apache/activeio/packet/ByteArrayPacket.java
index 4a3215a..348d74a 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/ByteArrayPacket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/ByteArrayPacket.java
@@ -1,239 +1,239 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-import java.lang.reflect.Constructor;

-

-

-/**

- * Provides a Packet implementation that is directly backed by a <code>byte[]</code>.

- * 

- * @version $Revision$

- */

-final public class ByteArrayPacket implements Packet {

-

-    private final byte buffer[];

-

-    private final int offset;

-    private final int capacity;

-    private int position;

-    private int limit;

-    private int remaining;

-    

-

-    public ByteArrayPacket(byte buffer[]) {

-        this(buffer,0, buffer.length);

-    }

-    

-    public ByteArrayPacket(ByteSequence sequence) {

-        this(sequence.getData(), sequence.getOffset(), sequence.getLength());

-    }

-    

-    public ByteArrayPacket(byte buffer[], int offset, int capacity) {

-        this.buffer = buffer;

-        this.offset=offset;

-        this.capacity=capacity;

-		this.position = 0;

-		this.limit = capacity;

-		this.remaining = limit-position;

-    }

-

-    public int position() {

-        return position;

-    }

-

-    public void position(int position) {

-        this.position = position;

-        remaining = limit-position;

-    }

-

-    public int limit() {

-        return limit;

-    }

-

-    public void limit(int limit) {

-        this.limit = limit;

-        remaining = limit-position;

-    }

-

-    public void flip() {

-        limit = position;

-        position = 0;

-        remaining = limit - position;

-    }

-

-    public int remaining() {

-        return remaining;

-    }

-

-    public void rewind() {

-        position = 0;

-        remaining = limit - position;

-    }

-

-    public boolean hasRemaining() {

-        return remaining > 0;

-    }

-

-    public void clear() {

-        position = 0;

-        limit = capacity;

-        remaining = limit - position;

-    }

-

-    public int capacity() {

-        return capacity;

-    }

-

-    public Packet slice() {

-        return new ByteArrayPacket(buffer, offset+position, remaining);

-    }

-    

-    public Packet duplicate() {

-        return new ByteArrayPacket(buffer, offset, capacity);

-    }

-

-    public Object duplicate(ClassLoader cl) throws IOException {

-        try{

-            Class clazz = cl.loadClass(ByteArrayPacket.class.getName());

-            Constructor constructor = clazz.getConstructor(new Class[]{byte[].class, int.class, int.class});

-            return constructor.newInstance(new Object[]{buffer, new Integer(offset), new Integer(capacity())});

-        } catch (Throwable e) {

-            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);

-        }

-    }

-

-    public void writeTo(OutputStream out) throws IOException {

-        out.write(buffer, offset+position, remaining);

-        position=limit;

-        remaining = limit-position;

-    }

-    

-    public void writeTo(DataOutput out) throws IOException {

-        out.write(buffer, offset+position, remaining);

-        position=limit;

-        remaining = limit-position;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read()

-     */

-    public int read() {

-        if( !(remaining > 0) )

-            return -1;

-        int rc = buffer[offset+position];

-        position++;

-        remaining = limit-position;

-        return rc & 0xff;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)

-     */

-    public int read(byte[] data, int offset, int length) {

-        if( !(remaining > 0) )

-            return -1;

-        

-        int copyLength = ((length <= remaining) ? length : remaining);

-        System.arraycopy(buffer, this.offset+position, data, offset, copyLength);

-        position += copyLength;

-        remaining = limit-position;

-        return copyLength;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(int)

-     */

-    public boolean write(int data) {

-        if( !(remaining > 0) )

-            return false;

-        buffer[offset+position]=(byte) data;

-        position++;

-        remaining = limit-position;

-        return true;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)

-     */

-    public int write(byte[] data, int offset, int length) {

-        if( !(remaining > 0) )

-            return -1;

-        

-        int copyLength = ((length <= remaining) ? length : remaining);

-        System.arraycopy(data, offset, buffer, this.offset+position, copyLength);

-        position+=copyLength;

-        remaining = limit-position;

-        return copyLength;

-    }

-

-    public ByteSequence asByteSequence() {

-        return new ByteSequence(buffer, offset+position, remaining);

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#sliceAsBytes()

-     */

-    public byte[] sliceAsBytes() {

-        if( buffer.length == remaining ) {

-            return buffer;

-        } else {

-            byte rc[] = new byte[remaining];

-            int op = position;

-            read(rc,0,remaining);

-            position=op;

-            remaining = limit-position;

-            return rc;

-        }

-    }

-    

-    /**

-     * @param dest

-     * @return the number of bytes read into the dest.

-     */

-    public int read(Packet dest) {        

-	    int a = dest.remaining();

-		int rc = ((a <= remaining) ? a : remaining); 

-		if( rc > 0 ) {

-		    dest.write( buffer, offset+position, rc);

-		    position = position+rc;

-	        remaining = limit-position;

-		}

-		return rc;

-    }

-    

-    public String toString() {

-        return "{position="+position+",limit="+limit+",capacity="+capacity+"}";

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-    

-    public byte[] getBuffer() {

-        return buffer;

-    }

-    

-    public void dispose() {        

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+
+
+/**
+ * Provides a Packet implementation that is directly backed by a <code>byte[]</code>.
+ * 
+ * @version $Revision$
+ */
+final public class ByteArrayPacket implements Packet {
+
+    private final byte buffer[];
+
+    private final int offset;
+    private final int capacity;
+    private int position;
+    private int limit;
+    private int remaining;
+    
+
+    public ByteArrayPacket(byte buffer[]) {
+        this(buffer,0, buffer.length);
+    }
+    
+    public ByteArrayPacket(ByteSequence sequence) {
+        this(sequence.getData(), sequence.getOffset(), sequence.getLength());
+    }
+    
+    public ByteArrayPacket(byte buffer[], int offset, int capacity) {
+        this.buffer = buffer;
+        this.offset=offset;
+        this.capacity=capacity;
+		this.position = 0;
+		this.limit = capacity;
+		this.remaining = limit-position;
+    }
+
+    public int position() {
+        return position;
+    }
+
+    public void position(int position) {
+        this.position = position;
+        remaining = limit-position;
+    }
+
+    public int limit() {
+        return limit;
+    }
+
+    public void limit(int limit) {
+        this.limit = limit;
+        remaining = limit-position;
+    }
+
+    public void flip() {
+        limit = position;
+        position = 0;
+        remaining = limit - position;
+    }
+
+    public int remaining() {
+        return remaining;
+    }
+
+    public void rewind() {
+        position = 0;
+        remaining = limit - position;
+    }
+
+    public boolean hasRemaining() {
+        return remaining > 0;
+    }
+
+    public void clear() {
+        position = 0;
+        limit = capacity;
+        remaining = limit - position;
+    }
+
+    public int capacity() {
+        return capacity;
+    }
+
+    public Packet slice() {
+        return new ByteArrayPacket(buffer, offset+position, remaining);
+    }
+    
+    public Packet duplicate() {
+        return new ByteArrayPacket(buffer, offset, capacity);
+    }
+
+    public Object duplicate(ClassLoader cl) throws IOException {
+        try{
+            Class clazz = cl.loadClass(ByteArrayPacket.class.getName());
+            Constructor constructor = clazz.getConstructor(new Class[]{byte[].class, int.class, int.class});
+            return constructor.newInstance(new Object[]{buffer, new Integer(offset), new Integer(capacity())});
+        } catch (Throwable e) {
+            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);
+        }
+    }
+
+    public void writeTo(OutputStream out) throws IOException {
+        out.write(buffer, offset+position, remaining);
+        position=limit;
+        remaining = limit-position;
+    }
+    
+    public void writeTo(DataOutput out) throws IOException {
+        out.write(buffer, offset+position, remaining);
+        position=limit;
+        remaining = limit-position;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read()
+     */
+    public int read() {
+        if( !(remaining > 0) )
+            return -1;
+        int rc = buffer[offset+position];
+        position++;
+        remaining = limit-position;
+        return rc & 0xff;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)
+     */
+    public int read(byte[] data, int offset, int length) {
+        if( !(remaining > 0) )
+            return -1;
+        
+        int copyLength = ((length <= remaining) ? length : remaining);
+        System.arraycopy(buffer, this.offset+position, data, offset, copyLength);
+        position += copyLength;
+        remaining = limit-position;
+        return copyLength;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(int)
+     */
+    public boolean write(int data) {
+        if( !(remaining > 0) )
+            return false;
+        buffer[offset+position]=(byte) data;
+        position++;
+        remaining = limit-position;
+        return true;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)
+     */
+    public int write(byte[] data, int offset, int length) {
+        if( !(remaining > 0) )
+            return -1;
+        
+        int copyLength = ((length <= remaining) ? length : remaining);
+        System.arraycopy(data, offset, buffer, this.offset+position, copyLength);
+        position+=copyLength;
+        remaining = limit-position;
+        return copyLength;
+    }
+
+    public ByteSequence asByteSequence() {
+        return new ByteSequence(buffer, offset+position, remaining);
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#sliceAsBytes()
+     */
+    public byte[] sliceAsBytes() {
+        if( buffer.length == remaining ) {
+            return buffer;
+        } else {
+            byte rc[] = new byte[remaining];
+            int op = position;
+            read(rc,0,remaining);
+            position=op;
+            remaining = limit-position;
+            return rc;
+        }
+    }
+    
+    /**
+     * @param dest
+     * @return the number of bytes read into the dest.
+     */
+    public int read(Packet dest) {        
+	    int a = dest.remaining();
+		int rc = ((a <= remaining) ? a : remaining); 
+		if( rc > 0 ) {
+		    dest.write( buffer, offset+position, rc);
+		    position = position+rc;
+	        remaining = limit-position;
+		}
+		return rc;
+    }
+    
+    public String toString() {
+        return "{position="+position+",limit="+limit+",capacity="+capacity+"}";
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+    
+    public byte[] getBuffer() {
+        return buffer;
+    }
+    
+    public void dispose() {        
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacket.java b/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacket.java
index dfe65b3..9e08299 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacket.java
@@ -1,280 +1,280 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-import java.lang.reflect.Constructor;

-import java.nio.ByteBuffer;

-

-

-/**

- * Provides a Packet implementation that is backed by a {@see java.nio.ByteBuffer}

- * 

- * @version $Revision$

- */

-final public class ByteBufferPacket implements Packet {

-

-	public static final int DEFAULT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.DefaultByteBufferSize", ""+(64*1024)));

-	public static final int DEFAULT_DIRECT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.DefaultDirectByteBufferSize", ""+(8*1024)));

-

-    private final ByteBuffer buffer;

-    private static final int TEMP_BUFFER_SIZE = 64*1024;

-

-    public ByteBufferPacket(ByteBuffer buffer) {

-        this.buffer = buffer;

-        clear();

-    }

-    

-    public ByteBuffer getByteBuffer() {

-        return buffer;

-    }

-    

-    public static ByteBufferPacket createDefaultBuffer(boolean direct) {

-    	if( direct )

-    		return new ByteBufferPacket( ByteBuffer.allocateDirect(DEFAULT_DIRECT_BUFFER_SIZE) );

-    	return new ByteBufferPacket( ByteBuffer.allocate(DEFAULT_BUFFER_SIZE)  );

-    }

-    

-    public void writeTo(OutputStream out) throws IOException {

-        if( buffer.hasArray() ) {

-            

-            // If the buffer is backed by an array.. then use it directly.

-            out.write(buffer.array(), position(), remaining());

-            position(limit());

-            

-        } else {

-            

-            // It's not backed by a buffer.. We can only dump it to a OutputStream via a byte[] so,

-            // create a temp buffer that we can use to chunk it out.            

-            byte temp[] = new byte[TEMP_BUFFER_SIZE];            

-            while( buffer.hasRemaining() ) {

-                int maxWrite = buffer.remaining() > temp.length ? temp.length : buffer.remaining();

-	            buffer.get(temp, 0, maxWrite);

-	            out.write(temp,0, maxWrite);

-            }

-            

-        }        

-    }

-    

-    public void writeTo(DataOutput out) throws IOException {

-        if( buffer.hasArray() ) {

-            

-            // If the buffer is backed by an array.. then use it directly.

-            out.write(buffer.array(), position(), remaining());

-            position(limit());

-            

-        } else {

-            

-            // It's not backed by a buffer.. We can only dump it to a OutputStream via a byte[] so,

-            // create a temp buffer that we can use to chunk it out.            

-            byte temp[] = new byte[TEMP_BUFFER_SIZE];            

-            while( buffer.hasRemaining() ) {

-                int maxWrite = buffer.remaining() > temp.length ? temp.length : buffer.remaining();

-                buffer.get(temp, 0, maxWrite);

-                out.write(temp,0, maxWrite);

-            }

-            

-        }        

-    }

-

-    public int capacity() {

-        return buffer.capacity();

-    }

-

-    public void clear() {

-        buffer.clear();

-    }

-

-    public Packet compact() {

-        buffer.compact();

-        return this;

-    }

-

-    public void flip() {

-        buffer.flip();

-    }

-

-    public boolean hasRemaining() {

-        return buffer.hasRemaining();

-    }

-

-    public boolean isDirect() {

-        return buffer.isDirect();

-    }

-

-    public boolean isReadOnly() {

-        return buffer.isReadOnly();

-    }

-

-    public int limit() {

-        return buffer.limit();

-    }

-

-    public void limit(int arg0) {

-        buffer.limit(arg0);

-    }

-

-    public Packet mark() {

-        buffer.mark();

-        return this;

-    }

-

-    public int position() {

-        return buffer.position();

-    }

-

-    public void position(int arg0) {

-        buffer.position(arg0);

-    }

-

-    public int remaining() {

-        return buffer.remaining();

-    }

-

-    public void rewind() {

-        buffer.rewind();

-    }

-

-    public Packet slice() {

-        return new ByteBufferPacket(buffer.slice());

-    }

-

-    public Packet duplicate() {

-        return new ByteBufferPacket(buffer.duplicate());

-    }

-

-    public Object duplicate(ClassLoader cl) throws IOException {

-        try {

-            Class clazz = cl.loadClass(ByteBufferPacket.class.getName());

-            Constructor constructor = clazz.getConstructor(new Class[]{ByteBuffer.class});

-            return constructor.newInstance(new Object[]{buffer.duplicate()});

-        } catch (Throwable e) {

-            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);

-        }

-

-    }

-    

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read()

-     */

-    public int read() {

-        if( !buffer.hasRemaining() )

-            return -1;

-        return buffer.get() & 0xff;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)

-     */

-    public int read(byte[] data, int offset, int length) {

-        if( !hasRemaining() )

-            return -1;

-        

-        int copyLength = Math.min(length, remaining());

-        buffer.get(data, offset, copyLength);

-        return copyLength;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(int)

-     */

-    public boolean write(int data) {

-        if( !buffer.hasRemaining() )

-            return false;

-        buffer.put((byte)data);

-        return true;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)

-     */

-    public int write(byte[] data, int offset, int length) {

-        if( !hasRemaining() )

-            return -1;

-

-        int copyLength = Math.min(length, remaining());

-        buffer.put(data, offset, copyLength);

-        return copyLength;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#asByteSequence()

-     */

-    public ByteSequence asByteSequence() {

-        if( buffer.hasArray() ) {

-            byte[] bs = buffer.array();

-            return new ByteSequence(bs, buffer.position(), buffer.remaining());

-        }

-        // TODO: implement the direct case.

-        return null;

-    }

-    

-    /**

-     * @see org.apache.activeio.packet.Packet#sliceAsBytes()

-     */

-    public byte[] sliceAsBytes() {

-        // TODO Auto-generated method stub

-        return null;

-    }

-

-    /**

-     * @param dest

-     * @return the number of bytes read into the dest.

-     */

-    public int read(Packet dest) {

-        

-	    int rc = Math.min(dest.remaining(), remaining()); 

-		if( rc > 0 ) {

-		    

-	        if( dest.getClass() == ByteBufferPacket.class ) {            

-

-			    // Adjust our limit so that we don't overflow the dest buffer. 

-				int limit = limit();

-				limit(position()+rc);

-				

-	            ((ByteBufferPacket)dest).buffer.put(buffer);

-

-	            // restore the limit.

-				limit(limit);

-	            

-	            return 0;

-	        } else {	            

-	            ByteSequence sequence = dest.asByteSequence();

-	            rc = read(sequence.getData(), sequence.getOffset(), sequence.getLength());

-	            dest.position(dest.position()+rc);

-	        }

-		}

-		return rc;

-    }

-	

-    public String toString() {

-        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-    

-    public void dispose() {        

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+import java.nio.ByteBuffer;
+
+
+/**
+ * Provides a Packet implementation that is backed by a {@see java.nio.ByteBuffer}
+ * 
+ * @version $Revision$
+ */
+final public class ByteBufferPacket implements Packet {
+
+	public static final int DEFAULT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.DefaultByteBufferSize", ""+(64*1024)));
+	public static final int DEFAULT_DIRECT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.DefaultDirectByteBufferSize", ""+(8*1024)));
+
+    private final ByteBuffer buffer;
+    private static final int TEMP_BUFFER_SIZE = 64*1024;
+
+    public ByteBufferPacket(ByteBuffer buffer) {
+        this.buffer = buffer;
+        clear();
+    }
+    
+    public ByteBuffer getByteBuffer() {
+        return buffer;
+    }
+    
+    public static ByteBufferPacket createDefaultBuffer(boolean direct) {
+    	if( direct )
+    		return new ByteBufferPacket( ByteBuffer.allocateDirect(DEFAULT_DIRECT_BUFFER_SIZE) );
+    	return new ByteBufferPacket( ByteBuffer.allocate(DEFAULT_BUFFER_SIZE)  );
+    }
+    
+    public void writeTo(OutputStream out) throws IOException {
+        if( buffer.hasArray() ) {
+            
+            // If the buffer is backed by an array.. then use it directly.
+            out.write(buffer.array(), position(), remaining());
+            position(limit());
+            
+        } else {
+            
+            // It's not backed by a buffer.. We can only dump it to a OutputStream via a byte[] so,
+            // create a temp buffer that we can use to chunk it out.            
+            byte temp[] = new byte[TEMP_BUFFER_SIZE];            
+            while( buffer.hasRemaining() ) {
+                int maxWrite = buffer.remaining() > temp.length ? temp.length : buffer.remaining();
+	            buffer.get(temp, 0, maxWrite);
+	            out.write(temp,0, maxWrite);
+            }
+            
+        }        
+    }
+    
+    public void writeTo(DataOutput out) throws IOException {
+        if( buffer.hasArray() ) {
+            
+            // If the buffer is backed by an array.. then use it directly.
+            out.write(buffer.array(), position(), remaining());
+            position(limit());
+            
+        } else {
+            
+            // It's not backed by a buffer.. We can only dump it to a OutputStream via a byte[] so,
+            // create a temp buffer that we can use to chunk it out.            
+            byte temp[] = new byte[TEMP_BUFFER_SIZE];            
+            while( buffer.hasRemaining() ) {
+                int maxWrite = buffer.remaining() > temp.length ? temp.length : buffer.remaining();
+                buffer.get(temp, 0, maxWrite);
+                out.write(temp,0, maxWrite);
+            }
+            
+        }        
+    }
+
+    public int capacity() {
+        return buffer.capacity();
+    }
+
+    public void clear() {
+        buffer.clear();
+    }
+
+    public Packet compact() {
+        buffer.compact();
+        return this;
+    }
+
+    public void flip() {
+        buffer.flip();
+    }
+
+    public boolean hasRemaining() {
+        return buffer.hasRemaining();
+    }
+
+    public boolean isDirect() {
+        return buffer.isDirect();
+    }
+
+    public boolean isReadOnly() {
+        return buffer.isReadOnly();
+    }
+
+    public int limit() {
+        return buffer.limit();
+    }
+
+    public void limit(int arg0) {
+        buffer.limit(arg0);
+    }
+
+    public Packet mark() {
+        buffer.mark();
+        return this;
+    }
+
+    public int position() {
+        return buffer.position();
+    }
+
+    public void position(int arg0) {
+        buffer.position(arg0);
+    }
+
+    public int remaining() {
+        return buffer.remaining();
+    }
+
+    public void rewind() {
+        buffer.rewind();
+    }
+
+    public Packet slice() {
+        return new ByteBufferPacket(buffer.slice());
+    }
+
+    public Packet duplicate() {
+        return new ByteBufferPacket(buffer.duplicate());
+    }
+
+    public Object duplicate(ClassLoader cl) throws IOException {
+        try {
+            Class clazz = cl.loadClass(ByteBufferPacket.class.getName());
+            Constructor constructor = clazz.getConstructor(new Class[]{ByteBuffer.class});
+            return constructor.newInstance(new Object[]{buffer.duplicate()});
+        } catch (Throwable e) {
+            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);
+        }
+
+    }
+    
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read()
+     */
+    public int read() {
+        if( !buffer.hasRemaining() )
+            return -1;
+        return buffer.get() & 0xff;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)
+     */
+    public int read(byte[] data, int offset, int length) {
+        if( !hasRemaining() )
+            return -1;
+        
+        int copyLength = Math.min(length, remaining());
+        buffer.get(data, offset, copyLength);
+        return copyLength;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(int)
+     */
+    public boolean write(int data) {
+        if( !buffer.hasRemaining() )
+            return false;
+        buffer.put((byte)data);
+        return true;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)
+     */
+    public int write(byte[] data, int offset, int length) {
+        if( !hasRemaining() )
+            return -1;
+
+        int copyLength = Math.min(length, remaining());
+        buffer.put(data, offset, copyLength);
+        return copyLength;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#asByteSequence()
+     */
+    public ByteSequence asByteSequence() {
+        if( buffer.hasArray() ) {
+            byte[] bs = buffer.array();
+            return new ByteSequence(bs, buffer.position(), buffer.remaining());
+        }
+        // TODO: implement the direct case.
+        return null;
+    }
+    
+    /**
+     * @see org.apache.activeio.packet.Packet#sliceAsBytes()
+     */
+    public byte[] sliceAsBytes() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    /**
+     * @param dest
+     * @return the number of bytes read into the dest.
+     */
+    public int read(Packet dest) {
+        
+	    int rc = Math.min(dest.remaining(), remaining()); 
+		if( rc > 0 ) {
+		    
+	        if( dest.getClass() == ByteBufferPacket.class ) {            
+
+			    // Adjust our limit so that we don't overflow the dest buffer. 
+				int limit = limit();
+				limit(position()+rc);
+				
+	            ((ByteBufferPacket)dest).buffer.put(buffer);
+
+	            // restore the limit.
+				limit(limit);
+	            
+	            return 0;
+	        } else {	            
+	            ByteSequence sequence = dest.asByteSequence();
+	            rc = read(sequence.getData(), sequence.getOffset(), sequence.getLength());
+	            dest.position(dest.position()+rc);
+	        }
+		}
+		return rc;
+    }
+	
+    public String toString() {
+        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+    
+    public void dispose() {        
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacketPool.java b/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacketPool.java
index 9f0da89..5c2e460 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacketPool.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/ByteBufferPacketPool.java
@@ -1,46 +1,46 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-

-import java.nio.ByteBuffer;

-

-/**

- * Provides a simple pool of ByteBuffer objects.

- * 

- * @version $Revision: 1.1 $

- */

-final public class ByteBufferPacketPool extends PacketPool {

-        

-	private final int packetSize;

-	

-	/**

-	 * Creates a pool of <code>bufferCount</code> ByteBuffers that are 

-	 * directly allocated being <code>bufferSize</code> big.

-	 * 

-	 * @param packetCount the number of buffers that will be in the pool.

-	 * @param packetSize the size of the buffers that are in the pool.

-	 */

-	public ByteBufferPacketPool(int packetCount,int packetSize) {

-		super(packetCount);

-		this.packetSize = packetSize;

-	}

-	

-    protected Packet allocateNewPacket() {

-        return new ByteBufferPacket(ByteBuffer.allocateDirect(packetSize));

-    }	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+
+import java.nio.ByteBuffer;
+
+/**
+ * Provides a simple pool of ByteBuffer objects.
+ * 
+ * @version $Revision: 1.1 $
+ */
+final public class ByteBufferPacketPool extends PacketPool {
+        
+	private final int packetSize;
+	
+	/**
+	 * Creates a pool of <code>bufferCount</code> ByteBuffers that are 
+	 * directly allocated being <code>bufferSize</code> big.
+	 * 
+	 * @param packetCount the number of buffers that will be in the pool.
+	 * @param packetSize the size of the buffers that are in the pool.
+	 */
+	public ByteBufferPacketPool(int packetCount,int packetSize) {
+		super(packetCount);
+		this.packetSize = packetSize;
+	}
+	
+    protected Packet allocateNewPacket() {
+        return new ByteBufferPacket(ByteBuffer.allocateDirect(packetSize));
+    }	
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/BytePacket.java b/activeio-core/src/main/java/org/apache/activeio/packet/BytePacket.java
index e59eb3e..7551336 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/BytePacket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/BytePacket.java
@@ -1,209 +1,209 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-import java.lang.reflect.Constructor;

-

-

-/**

- * Provides a Packet implementation that is directly backed by a <code>byte</code>.

- * 

- * @version $Revision$

- */

-final public class BytePacket implements Packet {

-

-    private byte data;

-    private byte position;

-    private byte limit;

-

-    public BytePacket(byte data) {

-        this.data = data;

-        clear();

-    }

-

-    public int position() {

-        return position;

-    }

-

-    public void position(int position) {

-        this.position = (byte) position;

-    }

-

-    public int limit() {

-        return limit;

-    }

-

-    public void limit(int limit) {

-        this.limit = (byte) limit;

-    }

-

-    public void flip() {

-        limit(position());

-        position(0);

-    }

-

-    public int remaining() {

-        return limit() - position();

-    }

-

-    public void rewind() {

-        position(0);

-    }

-

-    public boolean hasRemaining() {

-        return remaining() > 0;

-    }

-

-    public void clear() {

-        position(0);

-        limit(capacity());

-    }

-

-    public int capacity() {

-        return 1;

-    }

-

-    public Packet slice() {

-        if( hasRemaining() )

-            return new BytePacket(data);

-        return EmptyPacket.EMPTY_PACKET;

-    }

-    

-    public Packet duplicate() {

-        BytePacket packet = new BytePacket(data);

-        packet.limit(limit());

-        packet.position(position());

-        return packet;

-    }

-    

-    public Object duplicate(ClassLoader cl) throws IOException {

-        try {

-            Class clazz = cl.loadClass(BytePacket.class.getName());

-            Constructor constructor = clazz.getConstructor(new Class[]{byte.class});

-            return constructor.newInstance(new Object[]{new Byte(data)});

-        } catch (Throwable e) {

-            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);

-        }

-    }

-

-    public void writeTo(OutputStream out) throws IOException {

-        if( hasRemaining() ) {

-            out.write(data);

-            position(1);

-        }

-    }

-

-    public void writeTo(DataOutput out) throws IOException {

-        if( hasRemaining() ) {

-            out.write(data);

-            position(1);

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read()

-     */

-    public int read() {

-        if( !hasRemaining() )

-            return -1;

-        position(1);

-        return data & 0xff;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)

-     */

-    public int read(byte[] data, int offset, int length) {

-        if( !hasRemaining() )

-            return -1;

-        

-        if( length > 0 ) {

-            data[offset] = this.data;

-            position(1);

-            return 1;

-        }

-        return 0;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(int)

-     */

-    public boolean write(int data) {

-        if( !hasRemaining() )

-            return false;

-        

-        this.data = (byte) data; 

-        position(1);

-        return true;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)

-     */

-    public int write(byte[] data, int offset, int length) {

-        if( !hasRemaining() )

-            return -1;

-

-        if( length > 0 ) {

-            this.data = data[offset] ;

-            position(1);

-            return 1;

-        }

-        return 0;

-    }

-

-    public ByteSequence asByteSequence() {

-        return null;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#sliceAsBytes()

-     */

-    public byte[] sliceAsBytes() {

-        return null;

-    }

-    

-    /**

-     * @param dest

-     * @return the number of bytes read into the dest.

-     */

-    public int read(Packet dest) {

-        if( hasRemaining() ) {

-            dest.write(data);

-            position(1);

-            return 1;

-        }

-        return 0;

-    }

-    

-    public String toString() {

-        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-    

-    public void dispose() {        

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+
+
+/**
+ * Provides a Packet implementation that is directly backed by a <code>byte</code>.
+ * 
+ * @version $Revision$
+ */
+final public class BytePacket implements Packet {
+
+    private byte data;
+    private byte position;
+    private byte limit;
+
+    public BytePacket(byte data) {
+        this.data = data;
+        clear();
+    }
+
+    public int position() {
+        return position;
+    }
+
+    public void position(int position) {
+        this.position = (byte) position;
+    }
+
+    public int limit() {
+        return limit;
+    }
+
+    public void limit(int limit) {
+        this.limit = (byte) limit;
+    }
+
+    public void flip() {
+        limit(position());
+        position(0);
+    }
+
+    public int remaining() {
+        return limit() - position();
+    }
+
+    public void rewind() {
+        position(0);
+    }
+
+    public boolean hasRemaining() {
+        return remaining() > 0;
+    }
+
+    public void clear() {
+        position(0);
+        limit(capacity());
+    }
+
+    public int capacity() {
+        return 1;
+    }
+
+    public Packet slice() {
+        if( hasRemaining() )
+            return new BytePacket(data);
+        return EmptyPacket.EMPTY_PACKET;
+    }
+    
+    public Packet duplicate() {
+        BytePacket packet = new BytePacket(data);
+        packet.limit(limit());
+        packet.position(position());
+        return packet;
+    }
+    
+    public Object duplicate(ClassLoader cl) throws IOException {
+        try {
+            Class clazz = cl.loadClass(BytePacket.class.getName());
+            Constructor constructor = clazz.getConstructor(new Class[]{byte.class});
+            return constructor.newInstance(new Object[]{new Byte(data)});
+        } catch (Throwable e) {
+            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);
+        }
+    }
+
+    public void writeTo(OutputStream out) throws IOException {
+        if( hasRemaining() ) {
+            out.write(data);
+            position(1);
+        }
+    }
+
+    public void writeTo(DataOutput out) throws IOException {
+        if( hasRemaining() ) {
+            out.write(data);
+            position(1);
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read()
+     */
+    public int read() {
+        if( !hasRemaining() )
+            return -1;
+        position(1);
+        return data & 0xff;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)
+     */
+    public int read(byte[] data, int offset, int length) {
+        if( !hasRemaining() )
+            return -1;
+        
+        if( length > 0 ) {
+            data[offset] = this.data;
+            position(1);
+            return 1;
+        }
+        return 0;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(int)
+     */
+    public boolean write(int data) {
+        if( !hasRemaining() )
+            return false;
+        
+        this.data = (byte) data; 
+        position(1);
+        return true;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)
+     */
+    public int write(byte[] data, int offset, int length) {
+        if( !hasRemaining() )
+            return -1;
+
+        if( length > 0 ) {
+            this.data = data[offset] ;
+            position(1);
+            return 1;
+        }
+        return 0;
+    }
+
+    public ByteSequence asByteSequence() {
+        return null;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#sliceAsBytes()
+     */
+    public byte[] sliceAsBytes() {
+        return null;
+    }
+    
+    /**
+     * @param dest
+     * @return the number of bytes read into the dest.
+     */
+    public int read(Packet dest) {
+        if( hasRemaining() ) {
+            dest.write(data);
+            position(1);
+            return 1;
+        }
+        return 0;
+    }
+    
+    public String toString() {
+        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+    
+    public void dispose() {        
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/EOSPacket.java b/activeio-core/src/main/java/org/apache/activeio/packet/EOSPacket.java
index a875e95..60ddc1a 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/EOSPacket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/EOSPacket.java
@@ -1,151 +1,151 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-

-

-/**

- * Provides a Packet implementation that is used to represent the end of a stream.

- * 

- * @version $Revision$

- */

-final public class EOSPacket implements Packet {

-

-    static final public EOSPacket EOS_PACKET = new EOSPacket(); 

-    

-    private EOSPacket() {

-    }

-

-    public void writeTo(OutputStream out) throws IOException {

-    }

-    public void writeTo(DataOutput out) throws IOException {

-    }

-

-    public int position() {

-        return 1;

-    }

-

-    public void position(int position) {

-    }

-

-    public int limit() {

-        return 0;

-    }

-

-    public void limit(int limit) {

-    }

-

-    public void flip() {

-    }

-

-    public int remaining() {

-        return -1;

-    }

-

-    public void rewind() {

-    }

-

-    public boolean hasRemaining() {

-        return false;

-    }

-

-    public void clear() {

-    }

-

-    public int capacity() {

-        return 0;

-    }

-

-    public Packet slice() {

-        return this;

-    }

-    

-    public Packet duplicate() {

-        return this;               

-    }

-

-    public Object duplicate(ClassLoader cl) throws IOException {

-        try {

-            Class clazz = cl.loadClass(EOSPacket.class.getName());

-            return clazz.getField("EOS_PACKET").get(null);

-        } catch (Throwable e) {

-            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read()

-     */

-    public int read() {

-        return -1;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)

-     */

-    public int read(byte[] data, int offset, int length) {

-        return -1;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(int)

-     */

-    public boolean write(int data) {

-        return false;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)

-     */

-    public int write(byte[] data, int offset, int length) {

-        return -1;

-    }

-    

-    public ByteSequence asByteSequence() {

-        return EmptyPacket.EMPTY_BYTE_SEQUENCE;

-    }

-

-    public byte[] sliceAsBytes() {

-        return EmptyPacket.EMPTY_BYTE_ARRAY;

-    }

-    

-    /**

-     * @param dest

-     * @return the number of bytes read into the dest.

-     */

-    public int read(Packet dest) {        

-	    return 0;

-    }    

-    

-    public String toString() {

-        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-    

-    public void dispose() {        

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+
+
+/**
+ * Provides a Packet implementation that is used to represent the end of a stream.
+ * 
+ * @version $Revision$
+ */
+final public class EOSPacket implements Packet {
+
+    static final public EOSPacket EOS_PACKET = new EOSPacket(); 
+    
+    private EOSPacket() {
+    }
+
+    public void writeTo(OutputStream out) throws IOException {
+    }
+    public void writeTo(DataOutput out) throws IOException {
+    }
+
+    public int position() {
+        return 1;
+    }
+
+    public void position(int position) {
+    }
+
+    public int limit() {
+        return 0;
+    }
+
+    public void limit(int limit) {
+    }
+
+    public void flip() {
+    }
+
+    public int remaining() {
+        return -1;
+    }
+
+    public void rewind() {
+    }
+
+    public boolean hasRemaining() {
+        return false;
+    }
+
+    public void clear() {
+    }
+
+    public int capacity() {
+        return 0;
+    }
+
+    public Packet slice() {
+        return this;
+    }
+    
+    public Packet duplicate() {
+        return this;               
+    }
+
+    public Object duplicate(ClassLoader cl) throws IOException {
+        try {
+            Class clazz = cl.loadClass(EOSPacket.class.getName());
+            return clazz.getField("EOS_PACKET").get(null);
+        } catch (Throwable e) {
+            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read()
+     */
+    public int read() {
+        return -1;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)
+     */
+    public int read(byte[] data, int offset, int length) {
+        return -1;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(int)
+     */
+    public boolean write(int data) {
+        return false;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)
+     */
+    public int write(byte[] data, int offset, int length) {
+        return -1;
+    }
+    
+    public ByteSequence asByteSequence() {
+        return EmptyPacket.EMPTY_BYTE_SEQUENCE;
+    }
+
+    public byte[] sliceAsBytes() {
+        return EmptyPacket.EMPTY_BYTE_ARRAY;
+    }
+    
+    /**
+     * @param dest
+     * @return the number of bytes read into the dest.
+     */
+    public int read(Packet dest) {        
+	    return 0;
+    }    
+    
+    public String toString() {
+        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+    
+    public void dispose() {        
+    }
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/EmptyPacket.java b/activeio-core/src/main/java/org/apache/activeio/packet/EmptyPacket.java
index 42f2d60..17480de 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/EmptyPacket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/EmptyPacket.java
@@ -1,153 +1,153 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-

-

-/**

- * Provides a Packet implementation that is directly backed by a <code>byte[0]</code>.

- * 

- * @version $Revision$

- */

-final public class EmptyPacket implements Packet {

-

-    static final public EmptyPacket EMPTY_PACKET = new EmptyPacket(); 

-    static final byte EMPTY_BYTE_ARRAY[] = new byte[]{};

-    static final ByteSequence EMPTY_BYTE_SEQUENCE = new ByteSequence(EMPTY_BYTE_ARRAY,0,0);

-    

-    private EmptyPacket() {

-    }

-

-    public void writeTo(OutputStream out) throws IOException {

-    }

-    public void writeTo(DataOutput out) throws IOException {

-    }

-

-    public int position() {

-        return 0;

-    }

-

-    public void position(int position) {

-    }

-

-    public int limit() {

-        return 0;

-    }

-

-    public void limit(int limit) {

-    }

-

-    public void flip() {

-    }

-

-    public int remaining() {

-        return 0;

-    }

-

-    public void rewind() {

-    }

-

-    public boolean hasRemaining() {

-        return false;

-    }

-

-    public void clear() {

-    }

-

-    public int capacity() {

-        return 0;

-    }

-

-    public Packet slice() {

-        return this;

-    }

-    

-    public Packet duplicate() {

-        return this;               

-    }

-    

-    public Object duplicate(ClassLoader cl) throws IOException {

-        try {

-            Class clazz = cl.loadClass(EmptyPacket.class.getName());

-            return clazz.getField("EMPTY_PACKET").get(null);

-        } catch (Throwable e) {

-            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read()

-     */

-    public int read() {

-        return -1;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)

-     */

-    public int read(byte[] data, int offset, int length) {

-        return -1;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(int)

-     */

-    public boolean write(int data) {

-        return false;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)

-     */

-    public int write(byte[] data, int offset, int length) {

-        return -1;

-    }

-    

-    public ByteSequence asByteSequence() {

-        return EMPTY_BYTE_SEQUENCE;

-    }

-

-    public byte[] sliceAsBytes() {

-        return EMPTY_BYTE_ARRAY;

-    }

-    

-    /**

-     * @param dest

-     * @return the number of bytes read into the dest.

-     */

-    public int read(Packet dest) {        

-	    return -1;

-    }    

-    

-    public String toString() {

-        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-    

-    public void dispose() {        

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+
+
+/**
+ * Provides a Packet implementation that is directly backed by a <code>byte[0]</code>.
+ * 
+ * @version $Revision$
+ */
+final public class EmptyPacket implements Packet {
+
+    static final public EmptyPacket EMPTY_PACKET = new EmptyPacket(); 
+    static final byte EMPTY_BYTE_ARRAY[] = new byte[]{};
+    static final ByteSequence EMPTY_BYTE_SEQUENCE = new ByteSequence(EMPTY_BYTE_ARRAY,0,0);
+    
+    private EmptyPacket() {
+    }
+
+    public void writeTo(OutputStream out) throws IOException {
+    }
+    public void writeTo(DataOutput out) throws IOException {
+    }
+
+    public int position() {
+        return 0;
+    }
+
+    public void position(int position) {
+    }
+
+    public int limit() {
+        return 0;
+    }
+
+    public void limit(int limit) {
+    }
+
+    public void flip() {
+    }
+
+    public int remaining() {
+        return 0;
+    }
+
+    public void rewind() {
+    }
+
+    public boolean hasRemaining() {
+        return false;
+    }
+
+    public void clear() {
+    }
+
+    public int capacity() {
+        return 0;
+    }
+
+    public Packet slice() {
+        return this;
+    }
+    
+    public Packet duplicate() {
+        return this;               
+    }
+    
+    public Object duplicate(ClassLoader cl) throws IOException {
+        try {
+            Class clazz = cl.loadClass(EmptyPacket.class.getName());
+            return clazz.getField("EMPTY_PACKET").get(null);
+        } catch (Throwable e) {
+            throw (IOException)new IOException("Could not duplicate packet in a different classloader: "+e).initCause(e);
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read()
+     */
+    public int read() {
+        return -1;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#read(byte[], int, int)
+     */
+    public int read(byte[] data, int offset, int length) {
+        return -1;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(int)
+     */
+    public boolean write(int data) {
+        return false;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.Packet#write(byte[], int, int)
+     */
+    public int write(byte[] data, int offset, int length) {
+        return -1;
+    }
+    
+    public ByteSequence asByteSequence() {
+        return EMPTY_BYTE_SEQUENCE;
+    }
+
+    public byte[] sliceAsBytes() {
+        return EMPTY_BYTE_ARRAY;
+    }
+    
+    /**
+     * @param dest
+     * @return the number of bytes read into the dest.
+     */
+    public int read(Packet dest) {        
+	    return -1;
+    }    
+    
+    public String toString() {
+        return "{position="+position()+",limit="+limit()+",capacity="+capacity()+"}";
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+    
+    public void dispose() {        
+    }
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/FilterPacket.java b/activeio-core/src/main/java/org/apache/activeio/packet/FilterPacket.java
index 05a93a7..94dff7e 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/FilterPacket.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/FilterPacket.java
@@ -1,137 +1,137 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-

-

-/**

- * Provides a Packet implementation that filters operations to another packet.

- * 

- * Used to make it easier to augment the {@see #narrow(Class)}method.

- * 

- * @version $Revision$

- */

-public abstract class FilterPacket implements Packet {

-    final protected Packet next;

-

-    public FilterPacket(Packet next) {

-        this.next = next;

-    }

-

-    public ByteSequence asByteSequence() {

-        return next.asByteSequence();

-    }

-

-    public int capacity() {

-        return next.capacity();

-    }

-

-    public void clear() {

-        next.clear();

-    }

-

-    public void flip() {

-        next.flip();

-    }

-

-    public boolean hasRemaining() {

-        return next.hasRemaining();

-    }

-

-    public int limit() {

-        return next.limit();

-    }

-

-    public void limit(int limit) {

-        next.limit(limit);

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return next.getAdapter(target);

-    }

-

-    public int position() {

-        return next.position();

-    }

-

-    public void position(int position) {

-        next.position(position);

-    }

-

-    public int read() {

-        return next.read();

-    }

-

-    public int read(byte[] data, int offset, int length) {

-        return next.read(data, offset, length);

-    }

-

-    public int read(Packet dest) {

-        return next.read(dest);

-    }

-

-    public int remaining() {

-        return next.remaining();

-    }

-

-    public void rewind() {

-        next.rewind();

-    }

-

-    public byte[] sliceAsBytes() {

-        return next.sliceAsBytes();

-    }

-

-    public int write(byte[] data, int offset, int length) {

-        return next.write(data, offset, length);

-    }

-

-    public boolean write(int data) {

-        return next.write(data);

-    }

-

-    public void writeTo(OutputStream out) throws IOException {

-        next.writeTo(out);

-    }

-    public void writeTo(DataOutput out) throws IOException {

-        next.writeTo(out);

-    }

-

-    public Object duplicate(ClassLoader cl) throws IOException {

-        return next.duplicate(cl);

-    }

-

-    public Packet duplicate() {

-        return filter(next.duplicate());

-    }

-

-    public Packet slice() {

-        return filter(next.slice());

-    }

-    

-    public void dispose() {

-        next.dispose();

-    }

-

-    abstract public Packet filter(Packet packet);

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+
+
+/**
+ * Provides a Packet implementation that filters operations to another packet.
+ * 
+ * Used to make it easier to augment the {@see #narrow(Class)}method.
+ * 
+ * @version $Revision$
+ */
+public abstract class FilterPacket implements Packet {
+    final protected Packet next;
+
+    public FilterPacket(Packet next) {
+        this.next = next;
+    }
+
+    public ByteSequence asByteSequence() {
+        return next.asByteSequence();
+    }
+
+    public int capacity() {
+        return next.capacity();
+    }
+
+    public void clear() {
+        next.clear();
+    }
+
+    public void flip() {
+        next.flip();
+    }
+
+    public boolean hasRemaining() {
+        return next.hasRemaining();
+    }
+
+    public int limit() {
+        return next.limit();
+    }
+
+    public void limit(int limit) {
+        next.limit(limit);
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return next.getAdapter(target);
+    }
+
+    public int position() {
+        return next.position();
+    }
+
+    public void position(int position) {
+        next.position(position);
+    }
+
+    public int read() {
+        return next.read();
+    }
+
+    public int read(byte[] data, int offset, int length) {
+        return next.read(data, offset, length);
+    }
+
+    public int read(Packet dest) {
+        return next.read(dest);
+    }
+
+    public int remaining() {
+        return next.remaining();
+    }
+
+    public void rewind() {
+        next.rewind();
+    }
+
+    public byte[] sliceAsBytes() {
+        return next.sliceAsBytes();
+    }
+
+    public int write(byte[] data, int offset, int length) {
+        return next.write(data, offset, length);
+    }
+
+    public boolean write(int data) {
+        return next.write(data);
+    }
+
+    public void writeTo(OutputStream out) throws IOException {
+        next.writeTo(out);
+    }
+    public void writeTo(DataOutput out) throws IOException {
+        next.writeTo(out);
+    }
+
+    public Object duplicate(ClassLoader cl) throws IOException {
+        return next.duplicate(cl);
+    }
+
+    public Packet duplicate() {
+        return filter(next.duplicate());
+    }
+
+    public Packet slice() {
+        return filter(next.slice());
+    }
+    
+    public void dispose() {
+        next.dispose();
+    }
+
+    abstract public Packet filter(Packet packet);
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/Packet.java b/activeio-core/src/main/java/org/apache/activeio/packet/Packet.java
index 78d7816..4793105 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/Packet.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/Packet.java
@@ -1,69 +1,69 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.DataOutput;

-import java.io.IOException;

-import java.io.OutputStream;

-

-import org.apache.activeio.Adaptable;

-

-/**

- * Provides a ByteBuffer like interface to work with IO channel packets of data.

- * 

- * @version $Revision$

- */

-public interface Packet extends Adaptable {

-    

-    public int position();

-    public void position(int position);

-    public int limit();

-    public void limit(int limit);

-    public void flip();

-    public int remaining();

-    public void rewind();

-    public boolean hasRemaining();

-    public void clear();

-    public Packet slice();

-    public Packet duplicate();

-    public Object duplicate(ClassLoader cl) throws IOException;

-    public int capacity();

-    public void dispose();

-    

-    public ByteSequence asByteSequence();

-    public byte[] sliceAsBytes();

-    

-    

-    /**

-     * Writes the remaing bytes in the packet to the output stream.

-     * 

-     * @param out

-     * @return

-     */

-    void writeTo(OutputStream out) throws IOException;   

-    void writeTo(DataOutput out) throws IOException;

-    

-    // To read data out of the packet.

-    public int read();

-    public int read(byte data[], int offset, int length);

-

-    // To write data into the packet.

-    public boolean write( int data );

-    public int write( byte data[], int offset, int length );

-    public int read(Packet dest);

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.activeio.Adaptable;
+
+/**
+ * Provides a ByteBuffer like interface to work with IO channel packets of data.
+ * 
+ * @version $Revision$
+ */
+public interface Packet extends Adaptable {
+    
+    public int position();
+    public void position(int position);
+    public int limit();
+    public void limit(int limit);
+    public void flip();
+    public int remaining();
+    public void rewind();
+    public boolean hasRemaining();
+    public void clear();
+    public Packet slice();
+    public Packet duplicate();
+    public Object duplicate(ClassLoader cl) throws IOException;
+    public int capacity();
+    public void dispose();
+    
+    public ByteSequence asByteSequence();
+    public byte[] sliceAsBytes();
+    
+    
+    /**
+     * Writes the remaing bytes in the packet to the output stream.
+     * 
+     * @param out
+     * @return
+     */
+    void writeTo(OutputStream out) throws IOException;   
+    void writeTo(DataOutput out) throws IOException;
+    
+    // To read data out of the packet.
+    public int read();
+    public int read(byte data[], int offset, int length);
+
+    // To write data into the packet.
+    public boolean write( int data );
+    public int write( byte data[], int offset, int length );
+    public int read(Packet dest);
+    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/PacketData.java b/activeio-core/src/main/java/org/apache/activeio/packet/PacketData.java
index 32cf7bf..ecbaf54 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/PacketData.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/PacketData.java
@@ -1,381 +1,381 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.io.EOFException;

-import java.io.IOException;

-

-

-/**

- * Used to write and read primitives to and from a Packet.

- */

-final public class PacketData {

-

-    final private Packet packet;

-    private final boolean bigEndian;

-

-    public PacketData(Packet packet) {

-        this(packet, true);

-    }

-

-    public PacketData(Packet packet, boolean bigEndian) {

-        this.packet = packet;

-        this.bigEndian = bigEndian;

-    }

-

-    private static void spaceNeeded(Packet packet, int space) throws IOException {

-        if (packet.remaining() < space)

-            throw new EOFException("Not enough space left in the packet.");

-    }

-

-    public void readFully(byte[] b) throws IOException {

-        readFully(packet, b, 0, b.length);

-    }

-    

-    public static void readFully(Packet packet, byte[] b) throws IOException {

-        readFully(packet, b, 0, b.length);

-    }

-

-    public void readFully(byte[] b, int off, int len) throws IOException {

-        readFully(packet, b, off, len);

-    }

-    public static void readFully(Packet packet, byte[] b, int off, int len) throws IOException {

-        spaceNeeded(packet, len);

-        packet.read(b, off, len);

-    }

-

-    public int skipBytes(int n) throws IOException {

-        return skipBytes(packet, n);

-    }

-    public static int skipBytes(Packet packet, int n) throws IOException {

-        int rc = Math.min(n, packet.remaining());

-        packet.position(packet.position() + rc);

-        return rc;

-    }

-

-    public boolean readBoolean() throws IOException {

-        return readBoolean(packet);

-    }

-    public static boolean readBoolean(Packet packet) throws IOException {

-        spaceNeeded(packet, 1);

-        return packet.read() != 0;

-    }

-

-    public byte readByte() throws IOException {

-        return readByte(packet);

-    }

-    public static byte readByte(Packet packet) throws IOException {

-        spaceNeeded(packet, 1);

-        return (byte) packet.read();

-    }

-

-    public int readUnsignedByte() throws IOException {

-        return readUnsignedByte(packet);

-    }

-    public static int readUnsignedByte(Packet packet) throws IOException {

-        spaceNeeded(packet, 1);

-        return packet.read();

-    }

-

-    public short readShort() throws IOException {

-        if( bigEndian ) {

-            return readShortBig(packet);

-        } else {

-	        return readShortLittle(packet);

-        }        

-    }

-    public static short readShortBig(Packet packet) throws IOException {

-        spaceNeeded(packet, 2);

-        return (short) ((packet.read() << 8) + (packet.read() << 0));

-    }

-    public static short readShortLittle(Packet packet) throws IOException {

-        spaceNeeded(packet, 2);

-        return (short) ((packet.read() << 0) + (packet.read() << 8) );

-    }

-

-    public int readUnsignedShort() throws IOException {

-        if( bigEndian ) {

-            return readUnsignedShortBig(packet);

-        } else {

-	        return readUnsignedShortLittle(packet);

-        }        

-    }

-    public static int readUnsignedShortBig(Packet packet) throws IOException {

-        spaceNeeded(packet, 2);

-        return ((packet.read() << 8) + (packet.read() << 0));

-    }

-    public static int readUnsignedShortLittle(Packet packet) throws IOException {

-        spaceNeeded(packet, 2);

-        return ((packet.read() << 0) + (packet.read() << 8) );

-    }

-

-    public char readChar() throws IOException {

-        if( bigEndian ) {

-            return readCharBig(packet);

-        } else {

-	        return readCharLittle(packet);

-        }        

-    }

-    public static char readCharBig(Packet packet) throws IOException {

-        spaceNeeded(packet, 2);

-        return (char) ((packet.read() << 8) + (packet.read() << 0));

-    }

-    public static char readCharLittle(Packet packet) throws IOException {

-        spaceNeeded(packet, 2);

-        return (char) ((packet.read() << 0) + (packet.read() << 8) );

-    }

-

-    public int readInt() throws IOException {

-        if( bigEndian ) {

-	        return readIntBig(packet);

-        } else {

-	        return readIntLittle(packet);

-        }        

-    }    

-    public static int readIntBig(Packet packet) throws IOException {

-        spaceNeeded(packet, 4);

-        return ((packet.read() << 24) + 

-                (packet.read() << 16) + 

-                (packet.read() << 8) + 

-                (packet.read() << 0));

-    }    

-    public static int readIntLittle(Packet packet) throws IOException {

-        spaceNeeded(packet, 4);

-        return ((packet.read() << 0) +

-                (packet.read() << 8) + 

-                (packet.read() << 16) + 

-                (packet.read() << 24));

-    }    

-    

-    public long readLong() throws IOException {

-        if( bigEndian ) {

-	        return readLongBig(packet);

-        } else {

-	        return readLongLittle(packet);	                

-        }        

-    }

-    public static long readLongBig(Packet packet) throws IOException {

-        spaceNeeded(packet, 8);

-        return (((long) packet.read() << 56) + 

-                ((long) packet.read() << 48) + 

-                ((long) packet.read() << 40) + 

-                ((long) packet.read() << 32) + 

-                ((long) packet.read() << 24) + 

-                ((packet.read()) << 16) + 

-                ((packet.read()) << 8) + 

-                ((packet.read()) << 0));

-    }

-    public static long readLongLittle(Packet packet) throws IOException {

-        spaceNeeded(packet, 8);

-        return ((packet.read() << 0) +

-                (packet.read() << 8) + 

-                (packet.read() << 16) + 

-                ((long) packet.read() << 24) +

-                ((long) packet.read() << 32) + 

-                ((long) packet.read() << 40) + 

-                ((long) packet.read() << 48) + 

-                ((long) packet.read() << 56));                  

-    }

-    

-    public double readDouble() throws IOException {

-        return Double.longBitsToDouble(readLong());

-    }

-    public static double readDoubleBig(Packet packet) throws IOException {

-        return Double.longBitsToDouble(readLongBig(packet));

-    }

-    public static double readDoubleLittle(Packet packet) throws IOException {

-        return Double.longBitsToDouble(readLongLittle(packet));

-    }

-

-    public float readFloat() throws IOException {

-        return Float.intBitsToFloat(readInt());

-    }

-    public static float readFloatBig(Packet packet) throws IOException {

-        return Float.intBitsToFloat(readIntBig(packet));

-    }

-    public static float readFloatLittle(Packet packet) throws IOException {

-        return Float.intBitsToFloat(readIntLittle(packet));

-    }

-

-    public void write(int b) throws IOException {

-        write(packet, b);

-    }

-    public static void write(Packet packet, int b) throws IOException {

-        spaceNeeded(packet, 1);

-        packet.write(b);

-    }

-

-    public void write(byte[] b) throws IOException {

-        write(packet, b, 0, b.length);

-    }

-    public static void write(Packet packet, byte[] b) throws IOException {

-        write(packet, b, 0, b.length);

-    }

-

-    public void write(byte[] b, int off, int len) throws IOException {

-        write(packet, b, off, len);

-    }

-    public static void write(Packet packet, byte[] b, int off, int len) throws IOException {

-        spaceNeeded(packet, len);

-        packet.write(b, off, len);

-    }

-

-    public void writeBoolean(boolean v) throws IOException {

-        writeBoolean(packet, v);

-    }

-    public static void writeBoolean(Packet packet, boolean v) throws IOException {

-        spaceNeeded(packet, 1);

-        packet.write(v ? 1 : 0);

-    }

-

-    public void writeByte(int v) throws IOException {

-        writeByte(packet, v);

-    }

-    public static void writeByte(Packet packet, int v) throws IOException {

-        spaceNeeded(packet, 1);

-        packet.write(v);

-    }

-

-    public void writeShort(int v) throws IOException {

-        if (bigEndian) {

-	        writeShortBig(packet,v);

-	    } else {

-            writeShortLittle(packet,v);

-	    }

-    }

-    public static void writeShortBig(Packet packet, int v) throws IOException {

-        spaceNeeded(packet, 2);

-        packet.write((v >>> 8) & 0xFF);

-        packet.write((v >>> 0) & 0xFF);

-    }

-    public static void writeShortLittle(Packet packet, int v) throws IOException {

-        spaceNeeded(packet, 2);

-        packet.write((v >>> 0) & 0xFF);

-        packet.write((v >>> 8) & 0xFF);

-    }

-

-    public void writeChar(int v) throws IOException {

-        if (bigEndian) {

-            writeCharBig(packet, v);

-        } else {

-            writeCharLittle(packet, v);

-        }

-    }

-    public static void writeCharBig(Packet packet, int v) throws IOException {

-        spaceNeeded(packet, 2);

-        packet.write((v >>> 8) & 0xFF);

-        packet.write((v >>> 0) & 0xFF);

-    }

-    public static void writeCharLittle(Packet packet, int v) throws IOException {

-        spaceNeeded(packet, 2);

-        packet.write((v >>> 0) & 0xFF);

-        packet.write((v >>> 8) & 0xFF);

-    }

-

-    public void writeInt(int v) throws IOException {

-        if (bigEndian) {

-            writeIntBig(packet, v);

-        } else {

-            writeIntLittle(packet, v);

-        }

-    }

-    public static void writeIntBig(Packet packet, int v) throws IOException {

-        spaceNeeded(packet, 4);

-        packet.write((v >>> 24) & 0xFF);

-        packet.write((v >>> 16) & 0xFF);

-        packet.write((v >>> 8) & 0xFF);

-        packet.write((v >>> 0) & 0xFF);

-    }

-    public static void writeIntLittle(Packet packet, int v) throws IOException {

-        spaceNeeded(packet, 4);

-        packet.write((v >>> 0) & 0xFF);

-        packet.write((v >>> 8) & 0xFF);

-        packet.write((v >>> 16) & 0xFF);

-        packet.write((v >>> 24) & 0xFF);

-    }

-

-    public void writeLong(long v) throws IOException {

-        if (bigEndian) {

-            writeLongBig(packet, v);

-        } else {

-            writeLongLittle(packet, v);

-        }

-    }

-    public static void writeLongBig(Packet packet, long v) throws IOException {

-        spaceNeeded(packet, 8);

-        packet.write((int) (v >>> 56) & 0xFF);

-        packet.write((int) (v >>> 48) & 0xFF);

-        packet.write((int) (v >>> 40) & 0xFF);

-        packet.write((int) (v >>> 32) & 0xFF);

-        packet.write((int) (v >>> 24) & 0xFF);

-        packet.write((int) (v >>> 16) & 0xFF);

-        packet.write((int) (v >>> 8) & 0xFF);

-        packet.write((int) (v >>> 0) & 0xFF);

-    }

-    public static void writeLongLittle(Packet packet, long v) throws IOException {

-        spaceNeeded(packet, 8);

-        packet.write((int) (v >>> 0) & 0xFF);

-        packet.write((int) (v >>> 8) & 0xFF);

-        packet.write((int) (v >>> 16) & 0xFF);

-        packet.write((int) (v >>> 24) & 0xFF);

-        packet.write((int) (v >>> 32) & 0xFF);

-        packet.write((int) (v >>> 40) & 0xFF);

-        packet.write((int) (v >>> 48) & 0xFF);

-        packet.write((int) (v >>> 56) & 0xFF);

-    }

-    

-    public void writeDouble(double v) throws IOException {

-        writeLong(Double.doubleToLongBits(v));

-    }

-    public static void writeDoubleBig(Packet packet, double v) throws IOException {

-        writeLongBig(packet, Double.doubleToLongBits(v));

-    }

-    public static void writeDoubleLittle(Packet packet, double v) throws IOException {

-        writeLongLittle(packet, Double.doubleToLongBits(v));

-    }

-

-    public void writeFloat(float v) throws IOException {

-        writeInt(Float.floatToIntBits(v));

-    }

-    public static void writeFloatBig(Packet packet, float v) throws IOException {

-        writeIntBig(packet, Float.floatToIntBits(v));

-    }

-    public static void writeFloatLittle(Packet packet, float v) throws IOException {

-        writeIntLittle(packet, Float.floatToIntBits(v));

-    }

-    

-    public void writeRawDouble(double v) throws IOException {

-        writeLong(Double.doubleToRawLongBits(v));

-    }

-    public static void writeRawDoubleBig(Packet packet, double v) throws IOException {

-        writeLongBig(packet, Double.doubleToRawLongBits(v));

-    }

-    public static void writeRawDoubleLittle(Packet packet, double v) throws IOException {

-        writeLongLittle(packet, Double.doubleToRawLongBits(v));

-    }

-

-    public void writeRawFloat(float v) throws IOException {

-        writeInt(Float.floatToRawIntBits(v));

-    }

-    public static void writeRawFloatBig(Packet packet, float v) throws IOException {

-        writeIntBig(packet, Float.floatToRawIntBits(v));

-    }

-    public static void writeRawFloatLittle(Packet packet, float v) throws IOException {

-        writeIntLittle(packet, Float.floatToRawIntBits(v));

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.io.EOFException;
+import java.io.IOException;
+
+
+/**
+ * Used to write and read primitives to and from a Packet.
+ */
+final public class PacketData {
+
+    final private Packet packet;
+    private final boolean bigEndian;
+
+    public PacketData(Packet packet) {
+        this(packet, true);
+    }
+
+    public PacketData(Packet packet, boolean bigEndian) {
+        this.packet = packet;
+        this.bigEndian = bigEndian;
+    }
+
+    private static void spaceNeeded(Packet packet, int space) throws IOException {
+        if (packet.remaining() < space)
+            throw new EOFException("Not enough space left in the packet.");
+    }
+
+    public void readFully(byte[] b) throws IOException {
+        readFully(packet, b, 0, b.length);
+    }
+    
+    public static void readFully(Packet packet, byte[] b) throws IOException {
+        readFully(packet, b, 0, b.length);
+    }
+
+    public void readFully(byte[] b, int off, int len) throws IOException {
+        readFully(packet, b, off, len);
+    }
+    public static void readFully(Packet packet, byte[] b, int off, int len) throws IOException {
+        spaceNeeded(packet, len);
+        packet.read(b, off, len);
+    }
+
+    public int skipBytes(int n) throws IOException {
+        return skipBytes(packet, n);
+    }
+    public static int skipBytes(Packet packet, int n) throws IOException {
+        int rc = Math.min(n, packet.remaining());
+        packet.position(packet.position() + rc);
+        return rc;
+    }
+
+    public boolean readBoolean() throws IOException {
+        return readBoolean(packet);
+    }
+    public static boolean readBoolean(Packet packet) throws IOException {
+        spaceNeeded(packet, 1);
+        return packet.read() != 0;
+    }
+
+    public byte readByte() throws IOException {
+        return readByte(packet);
+    }
+    public static byte readByte(Packet packet) throws IOException {
+        spaceNeeded(packet, 1);
+        return (byte) packet.read();
+    }
+
+    public int readUnsignedByte() throws IOException {
+        return readUnsignedByte(packet);
+    }
+    public static int readUnsignedByte(Packet packet) throws IOException {
+        spaceNeeded(packet, 1);
+        return packet.read();
+    }
+
+    public short readShort() throws IOException {
+        if( bigEndian ) {
+            return readShortBig(packet);
+        } else {
+	        return readShortLittle(packet);
+        }        
+    }
+    public static short readShortBig(Packet packet) throws IOException {
+        spaceNeeded(packet, 2);
+        return (short) ((packet.read() << 8) + (packet.read() << 0));
+    }
+    public static short readShortLittle(Packet packet) throws IOException {
+        spaceNeeded(packet, 2);
+        return (short) ((packet.read() << 0) + (packet.read() << 8) );
+    }
+
+    public int readUnsignedShort() throws IOException {
+        if( bigEndian ) {
+            return readUnsignedShortBig(packet);
+        } else {
+	        return readUnsignedShortLittle(packet);
+        }        
+    }
+    public static int readUnsignedShortBig(Packet packet) throws IOException {
+        spaceNeeded(packet, 2);
+        return ((packet.read() << 8) + (packet.read() << 0));
+    }
+    public static int readUnsignedShortLittle(Packet packet) throws IOException {
+        spaceNeeded(packet, 2);
+        return ((packet.read() << 0) + (packet.read() << 8) );
+    }
+
+    public char readChar() throws IOException {
+        if( bigEndian ) {
+            return readCharBig(packet);
+        } else {
+	        return readCharLittle(packet);
+        }        
+    }
+    public static char readCharBig(Packet packet) throws IOException {
+        spaceNeeded(packet, 2);
+        return (char) ((packet.read() << 8) + (packet.read() << 0));
+    }
+    public static char readCharLittle(Packet packet) throws IOException {
+        spaceNeeded(packet, 2);
+        return (char) ((packet.read() << 0) + (packet.read() << 8) );
+    }
+
+    public int readInt() throws IOException {
+        if( bigEndian ) {
+	        return readIntBig(packet);
+        } else {
+	        return readIntLittle(packet);
+        }        
+    }    
+    public static int readIntBig(Packet packet) throws IOException {
+        spaceNeeded(packet, 4);
+        return ((packet.read() << 24) + 
+                (packet.read() << 16) + 
+                (packet.read() << 8) + 
+                (packet.read() << 0));
+    }    
+    public static int readIntLittle(Packet packet) throws IOException {
+        spaceNeeded(packet, 4);
+        return ((packet.read() << 0) +
+                (packet.read() << 8) + 
+                (packet.read() << 16) + 
+                (packet.read() << 24));
+    }    
+    
+    public long readLong() throws IOException {
+        if( bigEndian ) {
+	        return readLongBig(packet);
+        } else {
+	        return readLongLittle(packet);	                
+        }        
+    }
+    public static long readLongBig(Packet packet) throws IOException {
+        spaceNeeded(packet, 8);
+        return (((long) packet.read() << 56) + 
+                ((long) packet.read() << 48) + 
+                ((long) packet.read() << 40) + 
+                ((long) packet.read() << 32) + 
+                ((long) packet.read() << 24) + 
+                ((packet.read()) << 16) + 
+                ((packet.read()) << 8) + 
+                ((packet.read()) << 0));
+    }
+    public static long readLongLittle(Packet packet) throws IOException {
+        spaceNeeded(packet, 8);
+        return ((packet.read() << 0) +
+                (packet.read() << 8) + 
+                (packet.read() << 16) + 
+                ((long) packet.read() << 24) +
+                ((long) packet.read() << 32) + 
+                ((long) packet.read() << 40) + 
+                ((long) packet.read() << 48) + 
+                ((long) packet.read() << 56));                  
+    }
+    
+    public double readDouble() throws IOException {
+        return Double.longBitsToDouble(readLong());
+    }
+    public static double readDoubleBig(Packet packet) throws IOException {
+        return Double.longBitsToDouble(readLongBig(packet));
+    }
+    public static double readDoubleLittle(Packet packet) throws IOException {
+        return Double.longBitsToDouble(readLongLittle(packet));
+    }
+
+    public float readFloat() throws IOException {
+        return Float.intBitsToFloat(readInt());
+    }
+    public static float readFloatBig(Packet packet) throws IOException {
+        return Float.intBitsToFloat(readIntBig(packet));
+    }
+    public static float readFloatLittle(Packet packet) throws IOException {
+        return Float.intBitsToFloat(readIntLittle(packet));
+    }
+
+    public void write(int b) throws IOException {
+        write(packet, b);
+    }
+    public static void write(Packet packet, int b) throws IOException {
+        spaceNeeded(packet, 1);
+        packet.write(b);
+    }
+
+    public void write(byte[] b) throws IOException {
+        write(packet, b, 0, b.length);
+    }
+    public static void write(Packet packet, byte[] b) throws IOException {
+        write(packet, b, 0, b.length);
+    }
+
+    public void write(byte[] b, int off, int len) throws IOException {
+        write(packet, b, off, len);
+    }
+    public static void write(Packet packet, byte[] b, int off, int len) throws IOException {
+        spaceNeeded(packet, len);
+        packet.write(b, off, len);
+    }
+
+    public void writeBoolean(boolean v) throws IOException {
+        writeBoolean(packet, v);
+    }
+    public static void writeBoolean(Packet packet, boolean v) throws IOException {
+        spaceNeeded(packet, 1);
+        packet.write(v ? 1 : 0);
+    }
+
+    public void writeByte(int v) throws IOException {
+        writeByte(packet, v);
+    }
+    public static void writeByte(Packet packet, int v) throws IOException {
+        spaceNeeded(packet, 1);
+        packet.write(v);
+    }
+
+    public void writeShort(int v) throws IOException {
+        if (bigEndian) {
+	        writeShortBig(packet,v);
+	    } else {
+            writeShortLittle(packet,v);
+	    }
+    }
+    public static void writeShortBig(Packet packet, int v) throws IOException {
+        spaceNeeded(packet, 2);
+        packet.write((v >>> 8) & 0xFF);
+        packet.write((v >>> 0) & 0xFF);
+    }
+    public static void writeShortLittle(Packet packet, int v) throws IOException {
+        spaceNeeded(packet, 2);
+        packet.write((v >>> 0) & 0xFF);
+        packet.write((v >>> 8) & 0xFF);
+    }
+
+    public void writeChar(int v) throws IOException {
+        if (bigEndian) {
+            writeCharBig(packet, v);
+        } else {
+            writeCharLittle(packet, v);
+        }
+    }
+    public static void writeCharBig(Packet packet, int v) throws IOException {
+        spaceNeeded(packet, 2);
+        packet.write((v >>> 8) & 0xFF);
+        packet.write((v >>> 0) & 0xFF);
+    }
+    public static void writeCharLittle(Packet packet, int v) throws IOException {
+        spaceNeeded(packet, 2);
+        packet.write((v >>> 0) & 0xFF);
+        packet.write((v >>> 8) & 0xFF);
+    }
+
+    public void writeInt(int v) throws IOException {
+        if (bigEndian) {
+            writeIntBig(packet, v);
+        } else {
+            writeIntLittle(packet, v);
+        }
+    }
+    public static void writeIntBig(Packet packet, int v) throws IOException {
+        spaceNeeded(packet, 4);
+        packet.write((v >>> 24) & 0xFF);
+        packet.write((v >>> 16) & 0xFF);
+        packet.write((v >>> 8) & 0xFF);
+        packet.write((v >>> 0) & 0xFF);
+    }
+    public static void writeIntLittle(Packet packet, int v) throws IOException {
+        spaceNeeded(packet, 4);
+        packet.write((v >>> 0) & 0xFF);
+        packet.write((v >>> 8) & 0xFF);
+        packet.write((v >>> 16) & 0xFF);
+        packet.write((v >>> 24) & 0xFF);
+    }
+
+    public void writeLong(long v) throws IOException {
+        if (bigEndian) {
+            writeLongBig(packet, v);
+        } else {
+            writeLongLittle(packet, v);
+        }
+    }
+    public static void writeLongBig(Packet packet, long v) throws IOException {
+        spaceNeeded(packet, 8);
+        packet.write((int) (v >>> 56) & 0xFF);
+        packet.write((int) (v >>> 48) & 0xFF);
+        packet.write((int) (v >>> 40) & 0xFF);
+        packet.write((int) (v >>> 32) & 0xFF);
+        packet.write((int) (v >>> 24) & 0xFF);
+        packet.write((int) (v >>> 16) & 0xFF);
+        packet.write((int) (v >>> 8) & 0xFF);
+        packet.write((int) (v >>> 0) & 0xFF);
+    }
+    public static void writeLongLittle(Packet packet, long v) throws IOException {
+        spaceNeeded(packet, 8);
+        packet.write((int) (v >>> 0) & 0xFF);
+        packet.write((int) (v >>> 8) & 0xFF);
+        packet.write((int) (v >>> 16) & 0xFF);
+        packet.write((int) (v >>> 24) & 0xFF);
+        packet.write((int) (v >>> 32) & 0xFF);
+        packet.write((int) (v >>> 40) & 0xFF);
+        packet.write((int) (v >>> 48) & 0xFF);
+        packet.write((int) (v >>> 56) & 0xFF);
+    }
+    
+    public void writeDouble(double v) throws IOException {
+        writeLong(Double.doubleToLongBits(v));
+    }
+    public static void writeDoubleBig(Packet packet, double v) throws IOException {
+        writeLongBig(packet, Double.doubleToLongBits(v));
+    }
+    public static void writeDoubleLittle(Packet packet, double v) throws IOException {
+        writeLongLittle(packet, Double.doubleToLongBits(v));
+    }
+
+    public void writeFloat(float v) throws IOException {
+        writeInt(Float.floatToIntBits(v));
+    }
+    public static void writeFloatBig(Packet packet, float v) throws IOException {
+        writeIntBig(packet, Float.floatToIntBits(v));
+    }
+    public static void writeFloatLittle(Packet packet, float v) throws IOException {
+        writeIntLittle(packet, Float.floatToIntBits(v));
+    }
+    
+    public void writeRawDouble(double v) throws IOException {
+        writeLong(Double.doubleToRawLongBits(v));
+    }
+    public static void writeRawDoubleBig(Packet packet, double v) throws IOException {
+        writeLongBig(packet, Double.doubleToRawLongBits(v));
+    }
+    public static void writeRawDoubleLittle(Packet packet, double v) throws IOException {
+        writeLongLittle(packet, Double.doubleToRawLongBits(v));
+    }
+
+    public void writeRawFloat(float v) throws IOException {
+        writeInt(Float.floatToRawIntBits(v));
+    }
+    public static void writeRawFloatBig(Packet packet, float v) throws IOException {
+        writeIntBig(packet, Float.floatToRawIntBits(v));
+    }
+    public static void writeRawFloatLittle(Packet packet, float v) throws IOException {
+        writeIntLittle(packet, Float.floatToRawIntBits(v));
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/PacketPool.java b/activeio-core/src/main/java/org/apache/activeio/packet/PacketPool.java
index 598cc17..1c7bede 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/PacketPool.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/PacketPool.java
@@ -1,144 +1,144 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.util.ArrayList;

-

-import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;

-

-/**

- * Provides a simple pool of Packet objects.  When the packets that this pool produces are disposed,

- * they are returned to the pool.

- * 

- * @version $Revision: 1.1 $

- */

-abstract public class PacketPool {

-    

-    public static final int DEFAULT_POOL_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPoolSize", ""+(5)));

-    public static final int DEFAULT_PACKET_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPacketSize", ""+(1024*1024*4)));

-    

-	private final ArrayList pool = new ArrayList();

-	private final int maxPackets;

-    private int currentPoolSize;

-    private boolean disposed;

-    

-    public class PooledPacket extends FilterPacket {

-        private final AtomicInteger referenceCounter;

-        

-        public PooledPacket(Packet next) {

-            this(next, new AtomicInteger(0));

-        }

-        

-        private PooledPacket(Packet next, AtomicInteger referenceCounter) {

-            super(next);

-            this.referenceCounter=referenceCounter;

-            this.referenceCounter.incrementAndGet();

-        }

-        

-        public Packet filter(Packet packet) {

-            return new PooledPacket(next, referenceCounter);

-        }

-

-        int getReferenceCounter() {

-            return referenceCounter.get();

-        }

-        

-        public void dispose() {

-            if( referenceCounter.decrementAndGet()==0 ) {

-                returnPacket(next);

-            }

-        }

-    }

-	

-	/**

-	 * @param maxPackets the number of buffers that will be in the pool.

-	 */

-	public PacketPool(int maxPackets) {

-		this.maxPackets = maxPackets;

-	}

-	

-	/**

-	 * Blocks until a ByteBuffer can be retreived from the pool.

-	 * 

-	 * @return

-	 * @throws InterruptedException

-	 */

-	public Packet getPacket() throws InterruptedException {

-	    Packet answer=null;

-		synchronized(this) {

-			while(answer==null) {

-                 if( disposed )

-                     return null;                 

-				if( pool.size()>0) {

-					answer = (Packet) pool.remove(pool.size()-1);

-				} else if( currentPoolSize < maxPackets ) {

-                     answer = allocateNewPacket();

-                     currentPoolSize++;

-                 }

-				if( answer==null ) {

-					this.wait();

-				}

-			}

-		}

-		return new PooledPacket(answer);

-	}

-

-	/**

-	 * Returns a ByteBuffer to the pool.

-	 * 

-	 * @param packet

-	 */

-	private void returnPacket(Packet packet) {

-		packet.clear();

-		synchronized(this) {

-			pool.add(packet);

-			this.notify();

-		}

-	}

-    

-    synchronized public void dispose() {

-        disposed = true;

-        while( currentPoolSize>0 ) {

-            if( pool.size()>0) {

-                currentPoolSize -= pool.size();

-                pool.clear();

-            } else {

-                try {

-                    this.wait();

-                } catch (InterruptedException e) {

-                    return;

-                }

-            }

-        }

-    }

-    

-    synchronized public void waitForPacketsToReturn() {

-        while( currentPoolSize!=pool.size() ) {

-            try {

-                this.wait();

-            } catch (InterruptedException e) {

-                return;

-            }

-        }

-    }

-

-    /**

-     * @return

-     */

-    abstract protected Packet allocateNewPacket();

-        

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.util.ArrayList;
+
+import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Provides a simple pool of Packet objects.  When the packets that this pool produces are disposed,
+ * they are returned to the pool.
+ * 
+ * @version $Revision: 1.1 $
+ */
+abstract public class PacketPool {
+    
+    public static final int DEFAULT_POOL_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPoolSize", ""+(5)));
+    public static final int DEFAULT_PACKET_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.journal.active.DefaultPacketSize", ""+(1024*1024*4)));
+    
+	private final ArrayList pool = new ArrayList();
+	private final int maxPackets;
+    private int currentPoolSize;
+    private boolean disposed;
+    
+    public class PooledPacket extends FilterPacket {
+        private final AtomicInteger referenceCounter;
+        
+        public PooledPacket(Packet next) {
+            this(next, new AtomicInteger(0));
+        }
+        
+        private PooledPacket(Packet next, AtomicInteger referenceCounter) {
+            super(next);
+            this.referenceCounter=referenceCounter;
+            this.referenceCounter.incrementAndGet();
+        }
+        
+        public Packet filter(Packet packet) {
+            return new PooledPacket(next, referenceCounter);
+        }
+
+        int getReferenceCounter() {
+            return referenceCounter.get();
+        }
+        
+        public void dispose() {
+            if( referenceCounter.decrementAndGet()==0 ) {
+                returnPacket(next);
+            }
+        }
+    }
+	
+	/**
+	 * @param maxPackets the number of buffers that will be in the pool.
+	 */
+	public PacketPool(int maxPackets) {
+		this.maxPackets = maxPackets;
+	}
+	
+	/**
+	 * Blocks until a ByteBuffer can be retreived from the pool.
+	 * 
+	 * @return
+	 * @throws InterruptedException
+	 */
+	public Packet getPacket() throws InterruptedException {
+	    Packet answer=null;
+		synchronized(this) {
+			while(answer==null) {
+                 if( disposed )
+                     return null;                 
+				if( pool.size()>0) {
+					answer = (Packet) pool.remove(pool.size()-1);
+				} else if( currentPoolSize < maxPackets ) {
+                     answer = allocateNewPacket();
+                     currentPoolSize++;
+                 }
+				if( answer==null ) {
+					this.wait();
+				}
+			}
+		}
+		return new PooledPacket(answer);
+	}
+
+	/**
+	 * Returns a ByteBuffer to the pool.
+	 * 
+	 * @param packet
+	 */
+	private void returnPacket(Packet packet) {
+		packet.clear();
+		synchronized(this) {
+			pool.add(packet);
+			this.notify();
+		}
+	}
+    
+    synchronized public void dispose() {
+        disposed = true;
+        while( currentPoolSize>0 ) {
+            if( pool.size()>0) {
+                currentPoolSize -= pool.size();
+                pool.clear();
+            } else {
+                try {
+                    this.wait();
+                } catch (InterruptedException e) {
+                    return;
+                }
+            }
+        }
+    }
+    
+    synchronized public void waitForPacketsToReturn() {
+        while( currentPoolSize!=pool.size() ) {
+            try {
+                this.wait();
+            } catch (InterruptedException e) {
+                return;
+            }
+        }
+    }
+
+    /**
+     * @return
+     */
+    abstract protected Packet allocateNewPacket();
+        
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannel.java
index a79f920..d5855d5 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannel.java
@@ -1,61 +1,61 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async;

-

-import java.io.IOException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.Packet;

-

-

-/**

- * AsyncChannel objects asynchronously push 'up' {@see org.apache.activeio.Packet} objects

- * to a registered {@see org.apache.activeio.ChannelConsumer}.

- * 

- * @version $Revision$

- */

-public interface AsyncChannel extends Channel {

-    

-    /**

-     * Registers the {@see ChannelConsumer} that the protcol will use to deliver packets

-     * coming 'up' the channel.

-     *  

-     * @param packetListener

-     */

-    void setAsyncChannelListener(AsyncChannelListener channelListener);

-    

-    /**

-     * @return the registered Packet consumer

-     */

-    AsyncChannelListener getAsyncChannelListener();

-    

-    /**

-     * Sends a packet down the channel towards the media.

-     * 

-     * @param packet

-     * @throws IOException

-     */

-    void write(Packet packet) throws IOException;

-

-    /**

-     * Some channels may buffer data which may be sent down if flush() is called.

-     * 

-     * @throws IOException

-     */

-    void flush() throws IOException;    

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async;
+
+import java.io.IOException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ * AsyncChannel objects asynchronously push 'up' {@see org.apache.activeio.Packet} objects
+ * to a registered {@see org.apache.activeio.ChannelConsumer}.
+ * 
+ * @version $Revision$
+ */
+public interface AsyncChannel extends Channel {
+    
+    /**
+     * Registers the {@see ChannelConsumer} that the protcol will use to deliver packets
+     * coming 'up' the channel.
+     *  
+     * @param packetListener
+     */
+    void setAsyncChannelListener(AsyncChannelListener channelListener);
+    
+    /**
+     * @return the registered Packet consumer
+     */
+    AsyncChannelListener getAsyncChannelListener();
+    
+    /**
+     * Sends a packet down the channel towards the media.
+     * 
+     * @param packet
+     * @throws IOException
+     */
+    void write(Packet packet) throws IOException;
+
+    /**
+     * Some channels may buffer data which may be sent down if flush() is called.
+     * 
+     * @throws IOException
+     */
+    void flush() throws IOException;    
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelFactory.java
index d3c6f1e..1220319 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelFactory.java
@@ -1,47 +1,47 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async;

-

-import java.io.IOException;

-import java.net.URI;

-

-

-/**

- * AsyncChannelFactory objects can create {@see org.apache.activeio.AsyncChannel}

- * and {@see org.apache.activeio.AsyncChannelServer} objects. 

- * 

- * @version $Revision$

- */

-public interface AsyncChannelFactory {

-

-	/**

-     * Opens a connection to server.

-     * 

-     * @param location

-     * @return

-     */

-	public AsyncChannel openAsyncChannel(URI location) throws IOException;

-	

-	/**

-     * Binds a server at the URI location.

-     * 

-     * @param location

-     * @return

-     */

-	public AsyncChannelServer bindAsyncChannel(URI location) throws IOException;

-	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async;
+
+import java.io.IOException;
+import java.net.URI;
+
+
+/**
+ * AsyncChannelFactory objects can create {@see org.apache.activeio.AsyncChannel}
+ * and {@see org.apache.activeio.AsyncChannelServer} objects. 
+ * 
+ * @version $Revision$
+ */
+public interface AsyncChannelFactory {
+
+	/**
+     * Opens a connection to server.
+     * 
+     * @param location
+     * @return
+     */
+	public AsyncChannel openAsyncChannel(URI location) throws IOException;
+	
+	/**
+     * Binds a server at the URI location.
+     * 
+     * @param location
+     * @return
+     */
+	public AsyncChannelServer bindAsyncChannel(URI location) throws IOException;
+	
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelListener.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelListener.java
index 1181f0f..ac3fa87 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelListener.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelListener.java
@@ -1,50 +1,50 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.Packet;

-

-

-/**

- * A ChannelConsumer object is used to receive 'up' {@see org.apache.activeio.Packet} objects.

- * 

- * TODO: describe the threading model so that the implementor of this interface can know if

- * the methods in this interface can block for a long time or not.  I'm thinking that it would

- * be best if these methods are not allowed to block for a long time to encourage SEDA style 

- * processing.

- * 

- * @version $Revision$

- */

-public interface AsyncChannelListener {

-	

-	/**

-	 * A {@see AsyncChannel} will call this method to deliver an 'up' packet to a consumer. 

-	 *   

-	 * @param packet

-	 */

-    void onPacket(Packet packet);

-    

-    /**

-	 * A {@see AsyncChannel} will call this method when a async failure occurs in the channel. 

-     * 

-     * @param error the exception that describes the failure.

-     */

-    void onPacketError(IOException error);

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ * A ChannelConsumer object is used to receive 'up' {@see org.apache.activeio.Packet} objects.
+ * 
+ * TODO: describe the threading model so that the implementor of this interface can know if
+ * the methods in this interface can block for a long time or not.  I'm thinking that it would
+ * be best if these methods are not allowed to block for a long time to encourage SEDA style 
+ * processing.
+ * 
+ * @version $Revision$
+ */
+public interface AsyncChannelListener {
+	
+	/**
+	 * A {@see AsyncChannel} will call this method to deliver an 'up' packet to a consumer. 
+	 *   
+	 * @param packet
+	 */
+    void onPacket(Packet packet);
+    
+    /**
+	 * A {@see AsyncChannel} will call this method when a async failure occurs in the channel. 
+     * 
+     * @param error the exception that describes the failure.
+     */
+    void onPacketError(IOException error);
+    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelServer.java
index f2596a8..c056244 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/AsyncChannelServer.java
@@ -1,39 +1,39 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.ChannelServer;

-

-

-/**

- * AsyncChannelServer objects asynchronously accept and create {@see org.apache.activeio.Channel} objects

- * and then delivers those objects to a {@see org.apache.activeio.AcceptConsumer}.

- * 

- * @version $Revision$

- */

-public interface AsyncChannelServer extends ChannelServer {

-	

-	/**

-	 * Registers an AcceptListener which is notified of accepted channels.

-	 *  

-	 * @param acceptListener

-	 */

-    void setAcceptListener(AcceptListener acceptListener);

-

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.ChannelServer;
+
+
+/**
+ * AsyncChannelServer objects asynchronously accept and create {@see org.apache.activeio.Channel} objects
+ * and then delivers those objects to a {@see org.apache.activeio.AcceptConsumer}.
+ * 
+ * @version $Revision$
+ */
+public interface AsyncChannelServer extends ChannelServer {
+	
+	/**
+	 * Registers an AcceptListener which is notified of accepted channels.
+	 *  
+	 * @param acceptListener
+	 */
+    void setAcceptListener(AcceptListener acceptListener);
+
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannel.java
index e5c8023..7b3e7a8 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannel.java
@@ -1,123 +1,123 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.Packet;

-

-

-/**

- * A AsyncChannelFilter can be used as a filter between a {@see org.apache.activeio.AsyncChannel}

- * and it's {@see org.apache.activeio.ChannelConsumer}.  Most {@see org.apache.activeio.AsyncChannel}

- * that are not directly accessing the network will extends the AsyncChannelFilter since they act as a

- * filter between the client and the network.  O 

- * 

- * @version $Revision$

- */

-public class FilterAsyncChannel implements AsyncChannel, AsyncChannelListener {

-

-    final protected AsyncChannel next;

-    protected AsyncChannelListener channelListener;

-

-    public FilterAsyncChannel(AsyncChannel next) {

-        this.next = next;

-    }

-

-    /**

-     */

-    public void setAsyncChannelListener(AsyncChannelListener channelListener) {

-        this.channelListener = channelListener;

-        if (channelListener == null)

-            next.setAsyncChannelListener(null);

-        else

-            next.setAsyncChannelListener(this);

-    }

-

-    public void write(Packet packet) throws IOException {

-        next.write(packet);

-    }

-

-    public void flush() throws IOException {

-        next.flush();

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        next.dispose();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#start()

-     * @throws IOException if the next channel has not been set.

-     */

-    public void start() throws IOException {

-        if( next == null )

-            throw new IOException("The next channel has not been set.");

-        if( channelListener ==null )

-            throw new IOException("The UpPacketListener has not been set.");

-        next.start();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#stop()

-     */

-    public void stop() throws IOException {

-        next.stop();

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacket(org.apache.activeio.packet.Packet)

-     */

-    public void onPacket(Packet packet) {

-        channelListener.onPacket(packet);

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacketError(org.apache.activeio.ChannelException)

-     */

-    public void onPacketError(IOException error) {

-        channelListener.onPacketError(error);

-    }

-

-    /**

-     * @return Returns the next.

-     */

-    public AsyncChannel getNext() {

-        return next;

-    }

-

-    /**

-     * @return Returns the packetListener.

-     */

-    public AsyncChannelListener getAsyncChannelListener() {

-        return channelListener;

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return next.getAdapter(target);

-    }  

-    

-    public String toString() {

-        return next.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ * A AsyncChannelFilter can be used as a filter between a {@see org.apache.activeio.AsyncChannel}
+ * and it's {@see org.apache.activeio.ChannelConsumer}.  Most {@see org.apache.activeio.AsyncChannel}
+ * that are not directly accessing the network will extends the AsyncChannelFilter since they act as a
+ * filter between the client and the network.  O 
+ * 
+ * @version $Revision$
+ */
+public class FilterAsyncChannel implements AsyncChannel, AsyncChannelListener {
+
+    final protected AsyncChannel next;
+    protected AsyncChannelListener channelListener;
+
+    public FilterAsyncChannel(AsyncChannel next) {
+        this.next = next;
+    }
+
+    /**
+     */
+    public void setAsyncChannelListener(AsyncChannelListener channelListener) {
+        this.channelListener = channelListener;
+        if (channelListener == null)
+            next.setAsyncChannelListener(null);
+        else
+            next.setAsyncChannelListener(this);
+    }
+
+    public void write(Packet packet) throws IOException {
+        next.write(packet);
+    }
+
+    public void flush() throws IOException {
+        next.flush();
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        next.dispose();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#start()
+     * @throws IOException if the next channel has not been set.
+     */
+    public void start() throws IOException {
+        if( next == null )
+            throw new IOException("The next channel has not been set.");
+        if( channelListener ==null )
+            throw new IOException("The UpPacketListener has not been set.");
+        next.start();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#stop()
+     */
+    public void stop() throws IOException {
+        next.stop();
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacket(org.apache.activeio.packet.Packet)
+     */
+    public void onPacket(Packet packet) {
+        channelListener.onPacket(packet);
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.AsyncChannelListener#onPacketError(org.apache.activeio.ChannelException)
+     */
+    public void onPacketError(IOException error) {
+        channelListener.onPacketError(error);
+    }
+
+    /**
+     * @return Returns the next.
+     */
+    public AsyncChannel getNext() {
+        return next;
+    }
+
+    /**
+     * @return Returns the packetListener.
+     */
+    public AsyncChannelListener getAsyncChannelListener() {
+        return channelListener;
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return next.getAdapter(target);
+    }  
+    
+    public String toString() {
+        return next.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannelServer.java
index fb637b0..67a367f 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/FilterAsyncChannelServer.java
@@ -1,104 +1,104 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.Channel;

-

-

-/**

- * A AsyncChannelFilter can be used as a filter between a {@see org.apache.activeio.AsyncChannel}

- * and it's {@see org.apache.activeio.ChannelConsumer}.  Most {@see org.apache.activeio.AsyncChannel}

- * that are not directly accessing the network will extends the AsyncChannelFilter since they act as a

- * filter between the client and the network.  O 

- * 

- * @version $Revision$

- */

-public class FilterAsyncChannelServer implements AsyncChannelServer, AcceptListener {

-

-    final protected AsyncChannelServer next;

-    protected AcceptListener acceptListener;

-

-    public FilterAsyncChannelServer(AsyncChannelServer next) {

-        this.next = next;

-        if( next == null )

-            throw new IllegalArgumentException("The next AsyncChannelServer cannot be null.");

-    }

-

-    public void setAcceptListener(AcceptListener acceptListener) {

-        this.acceptListener = acceptListener;

-        if (acceptListener == null)

-            next.setAcceptListener(null);

-        else

-            next.setAcceptListener(this);

-        

-    }

-    

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        next.dispose();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#start()

-     * @throws IOException if the next channel has not been set.

-     */

-    public void start() throws IOException {

-        if( acceptListener ==null )

-            throw new IOException("The AcceptListener has not been set.");

-        next.start();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#stop()

-     */

-    public void stop() throws IOException {

-        next.stop();

-    }

-

-    public void onAccept(Channel channel) {

-        acceptListener.onAccept(channel);

-    }

-

-    public void onAcceptError(IOException error) {

-        acceptListener.onAcceptError(error);

-    }

-

-    public URI getBindURI() {

-        return next.getBindURI();

-    }

-

-    public URI getConnectURI() {

-        return next.getConnectURI();

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return next.getAdapter(target);

-    }    

-    

-    public String toString() {

-        return next.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.Channel;
+
+
+/**
+ * A AsyncChannelFilter can be used as a filter between a {@see org.apache.activeio.AsyncChannel}
+ * and it's {@see org.apache.activeio.ChannelConsumer}.  Most {@see org.apache.activeio.AsyncChannel}
+ * that are not directly accessing the network will extends the AsyncChannelFilter since they act as a
+ * filter between the client and the network.  O 
+ * 
+ * @version $Revision$
+ */
+public class FilterAsyncChannelServer implements AsyncChannelServer, AcceptListener {
+
+    final protected AsyncChannelServer next;
+    protected AcceptListener acceptListener;
+
+    public FilterAsyncChannelServer(AsyncChannelServer next) {
+        this.next = next;
+        if( next == null )
+            throw new IllegalArgumentException("The next AsyncChannelServer cannot be null.");
+    }
+
+    public void setAcceptListener(AcceptListener acceptListener) {
+        this.acceptListener = acceptListener;
+        if (acceptListener == null)
+            next.setAcceptListener(null);
+        else
+            next.setAcceptListener(this);
+        
+    }
+    
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        next.dispose();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#start()
+     * @throws IOException if the next channel has not been set.
+     */
+    public void start() throws IOException {
+        if( acceptListener ==null )
+            throw new IOException("The AcceptListener has not been set.");
+        next.start();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#stop()
+     */
+    public void stop() throws IOException {
+        next.stop();
+    }
+
+    public void onAccept(Channel channel) {
+        acceptListener.onAccept(channel);
+    }
+
+    public void onAcceptError(IOException error) {
+        acceptListener.onAcceptError(error);
+    }
+
+    public URI getBindURI() {
+        return next.getBindURI();
+    }
+
+    public URI getConnectURI() {
+        return next.getConnectURI();
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return next.getAdapter(target);
+    }    
+    
+    public String toString() {
+        return next.toString();
+    }
  }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/CounterAsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/CounterAsyncChannel.java
index 5682115..4cd9f23 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/CounterAsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/CounterAsyncChannel.java
@@ -1,73 +1,73 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.filter;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.FilterAsyncChannel;

-

-

-/**

- * A CounterAsyncChannel is a simple {@see org.apache.activeio.AsyncChannelFilter} 

- * that counts the number bytes that been sent down and up through the channel.

- * 

- * The {@see org.apache.activeio.counter.CounterAttribueEnum.COUNTER_INBOUND_COUNT}

- * and {@see org.apache.activeio.counter.CounterAttribueEnum.COUNTER_OUTBOUND_COUNT}

- * attributes can be used to find query the channel to get the current inbound and outbound

- * byte counts.

- * 

- * @version $Revision$

- */

-final public class CounterAsyncChannel extends FilterAsyncChannel {

-

-    long inBoundCounter = 0;

-

-    long outBoundCounter = 0;

-

-    /**

-     * @param next

-     */

-    public CounterAsyncChannel(AsyncChannel next) {

-        super(next);

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.FilterAsyncChannel#onPacket(org.apache.activeio.packet.Packet)

-     */

-    public void onPacket(Packet packet) {

-        inBoundCounter += packet.remaining();

-        super.onPacket(packet);

-    }

-

-    /**

-     * @see org.apache.activeio.packet.async.FilterAsyncChannel#write(org.apache.activeio.packet.Packet)

-     */

-    public void write(Packet packet) throws IOException {

-        outBoundCounter += packet.position();

-        super.write(packet);

-    }

-

-    public long getInBoundCounter() {

-        return inBoundCounter;

-    }

-    

-    public long getOutBoundCounter() {

-        return outBoundCounter;

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.filter;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.FilterAsyncChannel;
+
+
+/**
+ * A CounterAsyncChannel is a simple {@see org.apache.activeio.AsyncChannelFilter} 
+ * that counts the number bytes that been sent down and up through the channel.
+ * 
+ * The {@see org.apache.activeio.counter.CounterAttribueEnum.COUNTER_INBOUND_COUNT}
+ * and {@see org.apache.activeio.counter.CounterAttribueEnum.COUNTER_OUTBOUND_COUNT}
+ * attributes can be used to find query the channel to get the current inbound and outbound
+ * byte counts.
+ * 
+ * @version $Revision$
+ */
+final public class CounterAsyncChannel extends FilterAsyncChannel {
+
+    long inBoundCounter = 0;
+
+    long outBoundCounter = 0;
+
+    /**
+     * @param next
+     */
+    public CounterAsyncChannel(AsyncChannel next) {
+        super(next);
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.FilterAsyncChannel#onPacket(org.apache.activeio.packet.Packet)
+     */
+    public void onPacket(Packet packet) {
+        inBoundCounter += packet.remaining();
+        super.onPacket(packet);
+    }
+
+    /**
+     * @see org.apache.activeio.packet.async.FilterAsyncChannel#write(org.apache.activeio.packet.Packet)
+     */
+    public void write(Packet packet) throws IOException {
+        outBoundCounter += packet.position();
+        super.write(packet);
+    }
+
+    public long getInBoundCounter() {
+        return inBoundCounter;
+    }
+    
+    public long getOutBoundCounter() {
+        return outBoundCounter;
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/PacketAggregatingAsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/PacketAggregatingAsyncChannel.java
index abcfa75..fbb018c 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/PacketAggregatingAsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/PacketAggregatingAsyncChannel.java
@@ -1,65 +1,65 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.filter;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.FilterAsyncChannel;

-import org.apache.activeio.util.PacketAggregator;

-

-/**

- * This PacketAggregatingAsyncChannel can be used when the client is sending a

- * 'record' style packet down the channel stack and needs receiving end to

- * receive the same 'record' packets.

- * 

- * This is very useful since in general, a channel does not grantee that a

- * Packet that is sent down will not be fragmented or combined with other Packet

- * objects.

- * 

- * This {@see org.apache.activeio.AsyncChannel} adds a 4 byte header

- * to each packet that is sent down.

- * 

- * @version $Revision$

- */

-final public class PacketAggregatingAsyncChannel extends FilterAsyncChannel {

-

-    private final PacketAggregator aggregator = new PacketAggregator() {

-        protected void packetAssembled(Packet packet) {

-            getAsyncChannelListener().onPacket(packet);

-        }

-    };

-    

-    public PacketAggregatingAsyncChannel(AsyncChannel next) {

-        super(next);

-    }

-

-    public void onPacket(Packet packet) {

-        try {

-            aggregator.addRawPacket(packet);

-        } catch (IOException e) {

-            getAsyncChannelListener().onPacketError(e);

-        }

-    }    

-    

-    public void write(Packet packet) throws IOException {

-        getNext().write(aggregator.getHeader(packet));

-        getNext().write(packet);

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.filter;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.FilterAsyncChannel;
+import org.apache.activeio.util.PacketAggregator;
+
+/**
+ * This PacketAggregatingAsyncChannel can be used when the client is sending a
+ * 'record' style packet down the channel stack and needs receiving end to
+ * receive the same 'record' packets.
+ * 
+ * This is very useful since in general, a channel does not grantee that a
+ * Packet that is sent down will not be fragmented or combined with other Packet
+ * objects.
+ * 
+ * This {@see org.apache.activeio.AsyncChannel} adds a 4 byte header
+ * to each packet that is sent down.
+ * 
+ * @version $Revision$
+ */
+final public class PacketAggregatingAsyncChannel extends FilterAsyncChannel {
+
+    private final PacketAggregator aggregator = new PacketAggregator() {
+        protected void packetAssembled(Packet packet) {
+            getAsyncChannelListener().onPacket(packet);
+        }
+    };
+    
+    public PacketAggregatingAsyncChannel(AsyncChannel next) {
+        super(next);
+    }
+
+    public void onPacket(Packet packet) {
+        try {
+            aggregator.addRawPacket(packet);
+        } catch (IOException e) {
+            getAsyncChannelListener().onPacketError(e);
+        }
+    }    
+    
+    public void write(Packet packet) throws IOException {
+        getNext().write(aggregator.getHeader(packet));
+        getNext().write(packet);
+    }
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/SynchornizedAsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/SynchornizedAsyncChannel.java
index d32ceb2..1343709 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/SynchornizedAsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/SynchornizedAsyncChannel.java
@@ -1,84 +1,84 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.filter;

-

-import edu.emory.mathcs.backport.java.util.concurrent.locks.Lock;

-import edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.FilterAsyncChannel;

-

-import java.io.IOException;

-

-/**

- * Used to synchronize concurrent access to an ASynchChannel.  

- * 

- * Uses a {@see edu.emory.mathcs.backport.java.util.concurrent.Sync} object

- * for write operations.  All other operations such as {@see #stop(long)}

- * and {@see #stop} just do a normal java synchronization against the SynchornizedSynchChannel

- * object instance.  It is assumed that the Async message delivery is not 

- * concurrent and therefore does not require synchronization.

- * 

- */

-public class SynchornizedAsyncChannel extends FilterAsyncChannel {

-

-    private final Lock writeLock;

-

-    public SynchornizedAsyncChannel(AsyncChannel next) {

-        this(next, new ReentrantLock());

-    }

-    

-    public SynchornizedAsyncChannel(AsyncChannel next, Lock writeLock) {

-        super(next);

-        this.writeLock = writeLock;

-    }    

-    

-    public void write(Packet packet) throws IOException {

-        writeLock.lock();

-        try {

-            getNext().write(packet);            

-        } finally {

-            writeLock.unlock();

-        }

-    }

-    

-    public void flush() throws IOException {

-        writeLock.lock();

-        try {

-            getNext().flush();            

-        } finally {

-            writeLock.unlock();

-        }

-    }

-

-    synchronized public Object getAdapter(Class target) {

-        return super.getAdapter(target);

-    }

-

-    synchronized public void start() throws IOException {

-        super.start();

-    }

-

-    synchronized public void stop() throws IOException {

-        super.stop();

-    }

-    

-    public Lock getWriteLock() {

-        return writeLock;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.filter;
+
+import edu.emory.mathcs.backport.java.util.concurrent.locks.Lock;
+import edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.FilterAsyncChannel;
+
+import java.io.IOException;
+
+/**
+ * Used to synchronize concurrent access to an ASynchChannel.  
+ * 
+ * Uses a {@see edu.emory.mathcs.backport.java.util.concurrent.Sync} object
+ * for write operations.  All other operations such as {@see #stop(long)}
+ * and {@see #stop} just do a normal java synchronization against the SynchornizedSynchChannel
+ * object instance.  It is assumed that the Async message delivery is not 
+ * concurrent and therefore does not require synchronization.
+ * 
+ */
+public class SynchornizedAsyncChannel extends FilterAsyncChannel {
+
+    private final Lock writeLock;
+
+    public SynchornizedAsyncChannel(AsyncChannel next) {
+        this(next, new ReentrantLock());
+    }
+    
+    public SynchornizedAsyncChannel(AsyncChannel next, Lock writeLock) {
+        super(next);
+        this.writeLock = writeLock;
+    }    
+    
+    public void write(Packet packet) throws IOException {
+        writeLock.lock();
+        try {
+            getNext().write(packet);            
+        } finally {
+            writeLock.unlock();
+        }
+    }
+    
+    public void flush() throws IOException {
+        writeLock.lock();
+        try {
+            getNext().flush();            
+        } finally {
+            writeLock.unlock();
+        }
+    }
+
+    synchronized public Object getAdapter(Class target) {
+        return super.getAdapter(target);
+    }
+
+    synchronized public void start() throws IOException {
+        super.start();
+    }
+
+    synchronized public void stop() throws IOException {
+        super.stop();
+    }
+    
+    public Lock getWriteLock() {
+        return writeLock;
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/WriteBufferedAsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/WriteBufferedAsyncChannel.java
index 7fcfb13..20f1575 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/WriteBufferedAsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/filter/WriteBufferedAsyncChannel.java
@@ -1,70 +1,70 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.filter;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.FilterAsyncChannel;

-

-/**

- */

-public class WriteBufferedAsyncChannel extends FilterAsyncChannel {

-

-    private static final int DEFAULT_BUFFER_SIZE = 1024*64;

-    private final Packet buffer;

-    private final boolean enableDirectWrites;

-    

-    public WriteBufferedAsyncChannel(AsyncChannel channel) {

-        this(channel, new ByteArrayPacket(new byte[DEFAULT_BUFFER_SIZE]));

-    }

-    

-    public WriteBufferedAsyncChannel(AsyncChannel channel, Packet buffer) {

-        this(channel, buffer, true);

-    }

-

-    public WriteBufferedAsyncChannel(AsyncChannel channel, Packet buffer, boolean enableDirectWrites) {

-        super(channel);

-        this.buffer = buffer;

-        this.enableDirectWrites = enableDirectWrites;

-    }

-

-    public void write(Packet packet) throws IOException {

-        

-        while( packet.hasRemaining() ) {

-	        packet.read(buffer);

-	        if( !buffer.hasRemaining() ) {

-	            flush();

-	            

-	            // Should we just direct write the rest?

-	            if( enableDirectWrites && packet.remaining() > buffer.capacity()) {

-	                getNext().write(packet);

-	                return;

-	            }

-	        }

-        }

-        

-    }

-    

-    public void flush() throws IOException {

-        buffer.flip();

-        getNext().write(buffer);

-        buffer.clear();

-    }    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.filter;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.FilterAsyncChannel;
+
+/**
+ */
+public class WriteBufferedAsyncChannel extends FilterAsyncChannel {
+
+    private static final int DEFAULT_BUFFER_SIZE = 1024*64;
+    private final Packet buffer;
+    private final boolean enableDirectWrites;
+    
+    public WriteBufferedAsyncChannel(AsyncChannel channel) {
+        this(channel, new ByteArrayPacket(new byte[DEFAULT_BUFFER_SIZE]));
+    }
+    
+    public WriteBufferedAsyncChannel(AsyncChannel channel, Packet buffer) {
+        this(channel, buffer, true);
+    }
+
+    public WriteBufferedAsyncChannel(AsyncChannel channel, Packet buffer, boolean enableDirectWrites) {
+        super(channel);
+        this.buffer = buffer;
+        this.enableDirectWrites = enableDirectWrites;
+    }
+
+    public void write(Packet packet) throws IOException {
+        
+        while( packet.hasRemaining() ) {
+	        packet.read(buffer);
+	        if( !buffer.hasRemaining() ) {
+	            flush();
+	            
+	            // Should we just direct write the rest?
+	            if( enableDirectWrites && packet.remaining() > buffer.capacity()) {
+	                getNext().write(packet);
+	                return;
+	            }
+	        }
+        }
+        
+    }
+    
+    public void flush() throws IOException {
+        buffer.flip();
+        getNext().write(buffer);
+        buffer.clear();
+    }    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannel.java
index 5d1ff68..df49810 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannel.java
@@ -1,181 +1,181 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.nio;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-import java.net.SocketException;

-import java.nio.ByteBuffer;

-import java.nio.channels.SelectionKey;

-import java.nio.channels.SocketChannel;

-

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.ByteSequence;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelListener;

-import org.apache.activeio.packet.async.nio.NIOAsyncChannelSelectorManager.SelectorManagerListener;

-import org.apache.activeio.packet.async.nio.NIOAsyncChannelSelectorManager.SocketChannelAsyncChannelSelection;

-import org.apache.activeio.packet.sync.nio.NIOBaseChannel;

-

-/**

- * @version $Revision$

- */

-final public class NIOAsyncChannel extends NIOBaseChannel implements AsyncChannel {

-

-    private AsyncChannelListener channelListener;

-    private SocketChannelAsyncChannelSelection selection;

-    private ByteBuffer inputByteBuffer;

-    private boolean running;

-

-    public NIOAsyncChannel(SocketChannel socketChannel, boolean useDirect) throws IOException {

-        super(socketChannel, useDirect);

-

-        socketChannel.configureBlocking(false);                

-        selection = NIOAsyncChannelSelectorManager.register(socketChannel, new SelectorManagerListener(){

-            public void onSelect(SocketChannelAsyncChannelSelection selection) {

-                String origName = Thread.currentThread().getName();

-                if (selection.isReadable())

-                try {

-                    Thread.currentThread().setName(NIOAsyncChannel.this.toString());

-                    serviceRead();

-                 } catch ( Throwable e ) {

-                     System.err.println("ActiveIO unexpected error: ");

-                     e.printStackTrace(System.err);

-                 } finally {

-                     Thread.currentThread().setName(origName);

-                 }

-            }

-        });

-        

-    }

-    

-    private void serviceRead() {

-        try {

-            

-            while( true ) {

-            	

-	            if( inputByteBuffer==null || !inputByteBuffer.hasRemaining() ) {

-	                inputByteBuffer = allocateBuffer();

-	            }

-	

-	            int size = socketChannel.read(inputByteBuffer);

-	            if( size == -1 ) {

-	                this.channelListener.onPacket( EOSPacket.EOS_PACKET );

-	                selection.close();

-	                break;

-	            }

-

-	            if( size==0 ) {

-	                break;

-	            }

-	            

-	            // Per Mike Spile, some plaforms read 1 byte of data on the first read, and then

-	            // a but load of data on the second read.  Try to load the butload here

-	            if( size == 1 && inputByteBuffer.hasRemaining() ) {

-		            int size2 = socketChannel.read(inputByteBuffer);

-		            if( size2 > 0 )

-		            		size += size2;

-	            }

-	            

-	            ByteBuffer remaining = inputByteBuffer.slice();            

-	            Packet data = new ByteBufferPacket(((ByteBuffer)inputByteBuffer.flip()).slice());

-	            this.channelListener.onPacket( data );

-	                        

-	            // Keep the remaining buffer around to fill with data.

-	            inputByteBuffer = remaining;

-	            

-	            if( inputByteBuffer.hasRemaining() )

-	                break;

-            }

-            

-        } catch (IOException e) {

-            this.channelListener.onPacketError(e);

-        }

-    }

-    

-    synchronized public void write(Packet packet) throws IOException {

-        

-    	ByteBuffer data;

-        if( packet.getClass()==ByteBufferPacket.class ) {

-            data = ((ByteBufferPacket)packet).getByteBuffer();            

-        } else {

-        	ByteSequence sequence = packet.asByteSequence();

-        	data = ByteBuffer.wrap(sequence.getData(), sequence.getOffset(), sequence.getLength());

-        }

-

-        long delay=1;

-        while( data.hasRemaining() ) {

-	        

-            // Since the write is non-blocking, all the data may not have been written.

-            int r1 = data.remaining();        

-	        socketChannel.write( data );        

-	        int r2 = data.remaining();

-	        

-	        // We may need to do a little bit of sleeping to avoid a busy loop.

-            // Slow down if no data was written out.. 

-	        if( r2>0 && r1-r2==0 ) {

-	            try {

-                    // Use exponential rollback to increase sleep time.

-                    Thread.sleep(delay);

-                    delay *= 5;

-                    if( delay > 1000*1 ) {

-                        delay = 1000;

-                    }

-                } catch (InterruptedException e) {

-                    throw new InterruptedIOException();

-                }

-	        } else {

-	            delay = 1;

-	        }

-        }

-    }

-

-    public void flush() throws IOException {

-    }

-

-    public void setAsyncChannelListener(AsyncChannelListener channelListener) {

-        this.channelListener = channelListener;

-    }

-

-    public AsyncChannelListener getAsyncChannelListener() {

-        return channelListener;

-    }

-

-    public void dispose() {

-        if( running && channelListener!=null ) {

-            channelListener.onPacketError(new SocketException("Socket closed."));

-        }

-        selection.close();

-        super.dispose();

-    }

-

-    public void start() throws IOException {

-        if( running )

-            return;

-        running=true;

-        selection.setInterestOps(SelectionKey.OP_READ);

-    }

-

-    public void stop() throws IOException {

-        if( !running )

-            return;

-        running=false;

-        selection.setInterestOps(0);        

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.nio;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.SocketException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.SocketChannel;
+
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.ByteSequence;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelListener;
+import org.apache.activeio.packet.async.nio.NIOAsyncChannelSelectorManager.SelectorManagerListener;
+import org.apache.activeio.packet.async.nio.NIOAsyncChannelSelectorManager.SocketChannelAsyncChannelSelection;
+import org.apache.activeio.packet.sync.nio.NIOBaseChannel;
+
+/**
+ * @version $Revision$
+ */
+final public class NIOAsyncChannel extends NIOBaseChannel implements AsyncChannel {
+
+    private AsyncChannelListener channelListener;
+    private SocketChannelAsyncChannelSelection selection;
+    private ByteBuffer inputByteBuffer;
+    private boolean running;
+
+    public NIOAsyncChannel(SocketChannel socketChannel, boolean useDirect) throws IOException {
+        super(socketChannel, useDirect);
+
+        socketChannel.configureBlocking(false);                
+        selection = NIOAsyncChannelSelectorManager.register(socketChannel, new SelectorManagerListener(){
+            public void onSelect(SocketChannelAsyncChannelSelection selection) {
+                String origName = Thread.currentThread().getName();
+                if (selection.isReadable())
+                try {
+                    Thread.currentThread().setName(NIOAsyncChannel.this.toString());
+                    serviceRead();
+                 } catch ( Throwable e ) {
+                     System.err.println("ActiveIO unexpected error: ");
+                     e.printStackTrace(System.err);
+                 } finally {
+                     Thread.currentThread().setName(origName);
+                 }
+            }
+        });
+        
+    }
+    
+    private void serviceRead() {
+        try {
+            
+            while( true ) {
+            	
+	            if( inputByteBuffer==null || !inputByteBuffer.hasRemaining() ) {
+	                inputByteBuffer = allocateBuffer();
+	            }
+	
+	            int size = socketChannel.read(inputByteBuffer);
+	            if( size == -1 ) {
+	                this.channelListener.onPacket( EOSPacket.EOS_PACKET );
+	                selection.close();
+	                break;
+	            }
+
+	            if( size==0 ) {
+	                break;
+	            }
+	            
+	            // Per Mike Spile, some plaforms read 1 byte of data on the first read, and then
+	            // a but load of data on the second read.  Try to load the butload here
+	            if( size == 1 && inputByteBuffer.hasRemaining() ) {
+		            int size2 = socketChannel.read(inputByteBuffer);
+		            if( size2 > 0 )
+		            		size += size2;
+	            }
+	            
+	            ByteBuffer remaining = inputByteBuffer.slice();            
+	            Packet data = new ByteBufferPacket(((ByteBuffer)inputByteBuffer.flip()).slice());
+	            this.channelListener.onPacket( data );
+	                        
+	            // Keep the remaining buffer around to fill with data.
+	            inputByteBuffer = remaining;
+	            
+	            if( inputByteBuffer.hasRemaining() )
+	                break;
+            }
+            
+        } catch (IOException e) {
+            this.channelListener.onPacketError(e);
+        }
+    }
+    
+    synchronized public void write(Packet packet) throws IOException {
+        
+    	ByteBuffer data;
+        if( packet.getClass()==ByteBufferPacket.class ) {
+            data = ((ByteBufferPacket)packet).getByteBuffer();            
+        } else {
+        	ByteSequence sequence = packet.asByteSequence();
+        	data = ByteBuffer.wrap(sequence.getData(), sequence.getOffset(), sequence.getLength());
+        }
+
+        long delay=1;
+        while( data.hasRemaining() ) {
+	        
+            // Since the write is non-blocking, all the data may not have been written.
+            int r1 = data.remaining();        
+	        socketChannel.write( data );        
+	        int r2 = data.remaining();
+	        
+	        // We may need to do a little bit of sleeping to avoid a busy loop.
+            // Slow down if no data was written out.. 
+	        if( r2>0 && r1-r2==0 ) {
+	            try {
+                    // Use exponential rollback to increase sleep time.
+                    Thread.sleep(delay);
+                    delay *= 5;
+                    if( delay > 1000*1 ) {
+                        delay = 1000;
+                    }
+                } catch (InterruptedException e) {
+                    throw new InterruptedIOException();
+                }
+	        } else {
+	            delay = 1;
+	        }
+        }
+    }
+
+    public void flush() throws IOException {
+    }
+
+    public void setAsyncChannelListener(AsyncChannelListener channelListener) {
+        this.channelListener = channelListener;
+    }
+
+    public AsyncChannelListener getAsyncChannelListener() {
+        return channelListener;
+    }
+
+    public void dispose() {
+        if( running && channelListener!=null ) {
+            channelListener.onPacketError(new SocketException("Socket closed."));
+        }
+        selection.close();
+        super.dispose();
+    }
+
+    public void start() throws IOException {
+        if( running )
+            return;
+        running=true;
+        selection.setInterestOps(SelectionKey.OP_READ);
+    }
+
+    public void stop() throws IOException {
+        if( !running )
+            return;
+        running=false;
+        selection.setInterestOps(0);        
+    }
  }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelFactory.java
index c082e6b..ba2237b 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelFactory.java
@@ -1,131 +1,131 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.nio;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.InetSocketAddress;

-import java.net.URI;

-import java.net.URISyntaxException;

-import java.nio.channels.ServerSocketChannel;

-import java.nio.channels.SocketChannel;

-

-import org.apache.activeio.adapter.SyncToAsyncChannelServer;

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;

-import org.apache.activeio.util.URISupport;

-

-/**

- * A TcpAsyncChannelFactory creates {@see org.apache.activeio.net.TcpAsyncChannel}

- * and {@see org.apache.activeio.net.TcpAsyncChannelServer} objects.

- * 

- * @version $Revision$

- */

-public class NIOAsyncChannelFactory implements AsyncChannelFactory {

-    

-    protected static final int DEFAULT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.net.nio.BufferSize", ""+(64*1024)));

-

-    protected static final int DEFAULT_BACKLOG = 500;

-    boolean useDirectBuffers = true;

-    private final boolean createWriteBufferedChannels;

-    private int backlog = DEFAULT_BACKLOG;

-    

-    public NIOAsyncChannelFactory() {

-        this(true);

-    }

-    

-    public NIOAsyncChannelFactory(boolean createWriteBufferedChannels) {

-        this.createWriteBufferedChannels = createWriteBufferedChannels;

-    }

-    

-    

-    /**

-     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.

-     * 

-     * @see org.apache.activeio.AsyncChannelFactory#openAsyncChannel(java.net.URI)

-     */

-    public AsyncChannel openAsyncChannel(URI location) throws IOException {

-        SocketChannel channel = SocketChannel.open();

-        channel.connect(new InetSocketAddress(location.getHost(), location.getPort()));

-        return createAsyncChannel(channel);

-    }

-

-    /**

-     * @param channel

-     * @return

-     * @throws IOException

-     */

-    protected AsyncChannel createAsyncChannel(SocketChannel socketChannel) throws IOException {

-        AsyncChannel channel = new NIOAsyncChannel(socketChannel, useDirectBuffers);

-        if( createWriteBufferedChannels ) {

-            channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers), false);

-        }

-        return channel;

-    }

-

-    /**

-     * Binds a server socket a the {@param location}'s port. 

-     * 

-     * @see org.apache.activeio.AsyncChannelFactory#bindAsyncChannel(java.net.URI)

-     */

-    public AsyncChannelServer bindAsyncChannel(URI bindURI) throws IOException {

-        

-        String host = bindURI.getHost();

-        InetSocketAddress address;

-        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            

-            address = new InetSocketAddress(bindURI.getPort());

-        } else {

-            address = new InetSocketAddress(bindURI.getHost(), bindURI.getPort());

-        }

-        

-        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

-        serverSocketChannel.socket().bind(address,backlog);

-        

-        URI connectURI = bindURI;

-        try {

-//            connectURI = URISupport.changeHost(connectURI, InetAddress.getLocalHost().getHostName());

-            connectURI = URISupport.changePort(connectURI, serverSocketChannel.socket().getLocalPort());

-        } catch (URISyntaxException e) {

-            throw (IOException)new IOException("Could not build connect URI: "+e).initCause(e);

-        }

-        

-        // We won't use non blocking NIO for the server since you only need 1 thread for him anyways.

-        // Just resuing the SocketChannelSynchChannelServer.

-        return SyncToAsyncChannelServer.adapt( 

-                new NIOAsyncChannelServer(serverSocketChannel, bindURI, connectURI, createWriteBufferedChannels, useDirectBuffers));

-    }

-    

-    /**

-     * @return Returns the backlog.

-     */

-    public int getBacklog() {

-        return backlog;

-    }

-

-    /**

-     * @param backlog

-     *            The backlog to set.

-     */

-    public void setBacklog(int backlog) {

-        this.backlog = backlog;

-    }

-

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.nio;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+
+import org.apache.activeio.adapter.SyncToAsyncChannelServer;
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;
+import org.apache.activeio.util.URISupport;
+
+/**
+ * A TcpAsyncChannelFactory creates {@see org.apache.activeio.net.TcpAsyncChannel}
+ * and {@see org.apache.activeio.net.TcpAsyncChannelServer} objects.
+ * 
+ * @version $Revision$
+ */
+public class NIOAsyncChannelFactory implements AsyncChannelFactory {
+    
+    protected static final int DEFAULT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.net.nio.BufferSize", ""+(64*1024)));
+
+    protected static final int DEFAULT_BACKLOG = 500;
+    boolean useDirectBuffers = true;
+    private final boolean createWriteBufferedChannels;
+    private int backlog = DEFAULT_BACKLOG;
+    
+    public NIOAsyncChannelFactory() {
+        this(true);
+    }
+    
+    public NIOAsyncChannelFactory(boolean createWriteBufferedChannels) {
+        this.createWriteBufferedChannels = createWriteBufferedChannels;
+    }
+    
+    
+    /**
+     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
+     * 
+     * @see org.apache.activeio.AsyncChannelFactory#openAsyncChannel(java.net.URI)
+     */
+    public AsyncChannel openAsyncChannel(URI location) throws IOException {
+        SocketChannel channel = SocketChannel.open();
+        channel.connect(new InetSocketAddress(location.getHost(), location.getPort()));
+        return createAsyncChannel(channel);
+    }
+
+    /**
+     * @param channel
+     * @return
+     * @throws IOException
+     */
+    protected AsyncChannel createAsyncChannel(SocketChannel socketChannel) throws IOException {
+        AsyncChannel channel = new NIOAsyncChannel(socketChannel, useDirectBuffers);
+        if( createWriteBufferedChannels ) {
+            channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers), false);
+        }
+        return channel;
+    }
+
+    /**
+     * Binds a server socket a the {@param location}'s port. 
+     * 
+     * @see org.apache.activeio.AsyncChannelFactory#bindAsyncChannel(java.net.URI)
+     */
+    public AsyncChannelServer bindAsyncChannel(URI bindURI) throws IOException {
+        
+        String host = bindURI.getHost();
+        InetSocketAddress address;
+        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            
+            address = new InetSocketAddress(bindURI.getPort());
+        } else {
+            address = new InetSocketAddress(bindURI.getHost(), bindURI.getPort());
+        }
+        
+        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
+        serverSocketChannel.socket().bind(address,backlog);
+        
+        URI connectURI = bindURI;
+        try {
+//            connectURI = URISupport.changeHost(connectURI, InetAddress.getLocalHost().getHostName());
+            connectURI = URISupport.changePort(connectURI, serverSocketChannel.socket().getLocalPort());
+        } catch (URISyntaxException e) {
+            throw (IOException)new IOException("Could not build connect URI: "+e).initCause(e);
+        }
+        
+        // We won't use non blocking NIO for the server since you only need 1 thread for him anyways.
+        // Just resuing the SocketChannelSynchChannelServer.
+        return SyncToAsyncChannelServer.adapt( 
+                new NIOAsyncChannelServer(serverSocketChannel, bindURI, connectURI, createWriteBufferedChannels, useDirectBuffers));
+    }
+    
+    /**
+     * @return Returns the backlog.
+     */
+    public int getBacklog() {
+        return backlog;
+    }
+
+    /**
+     * @param backlog
+     *            The backlog to set.
+     */
+    public void setBacklog(int backlog) {
+        this.backlog = backlog;
+    }
+
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelSelectorManager.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelSelectorManager.java
index 6cf3a49..b90b585 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelSelectorManager.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelSelectorManager.java
@@ -1,254 +1,254 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.nio;

-

-import edu.emory.mathcs.backport.java.util.concurrent.Executor;

-import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;

-

-import org.apache.activeio.ChannelFactory;

-

-import java.io.IOException;

-import java.nio.channels.ClosedChannelException;

-import java.nio.channels.SelectionKey;

-import java.nio.channels.Selector;

-import java.nio.channels.SocketChannel;

-import java.util.Iterator;

-import java.util.LinkedList;

-import java.util.Set;

-

-/**

- * The SelectorManager will manage one Selector and the thread that checks the

- * selector.

- * 

- * We may need to consider running more than one thread to check the selector if

- * servicing the selector takes too long.

- * 

- * @version $Rev: 46019 $ $Date: 2004-09-14 05:56:06 -0400 (Tue, 14 Sep 2004) $

- */

-final public class NIOAsyncChannelSelectorManager {

-

-    static private Executor selectorExecutor = ChannelFactory.DEFAULT_EXECUTOR;

-    static private Executor channelExecutor = ChannelFactory.DEFAULT_EXECUTOR;

-    

-    static private LinkedList freeManagers = new LinkedList();

-    static private LinkedList fullManagers = new LinkedList();

-    private static final int MAX_CHANNELS_PER_SELECTOR  = 50;

-    

-    static {

-       String os = System.getProperty("os.name");

-       if( os.startsWith("Linux") ) {

-           channelExecutor = new ScheduledThreadPoolExecutor(1);

-       }

-    } 

-

-    public static interface SelectorManagerListener {

-        public void onSelect(SocketChannelAsyncChannelSelection selector);

-    }

-

-    final public class SocketChannelAsyncChannelSelection {

-        

-        private final SelectionKey key;

-        private final SelectorManagerListener listener;

-        private boolean closed;

-        private int interest;

-

-        private SocketChannelAsyncChannelSelection(SocketChannel socketChannel, SelectorManagerListener listener)

-                throws ClosedChannelException {

-            this.listener = listener;

-            this.key = socketChannel.register(selector, 0, this);

-            incrementUseCounter();

-        }

-

-        public void setInterestOps(int ops) {

-            	if( closed ) 

-            		return;

-            	interest = ops;

-             enable();

-        }

-        

-        public void enable() {

-            if( closed ) 

-                return;

-            key.interestOps(interest);

-            selector.wakeup();

-        }

-

-        public void disable() {

-            if( closed ) 

-                return;

-            key.interestOps(0);

-        }

-

-        public void close() {

-        	if( closed ) 

-        		return;

-        	

-            key.cancel();

-            decrementUseCounter();

-            selector.wakeup();

-            closed=true;

-        }

-        

-        public void onSelect() {

-            if( !key.isValid() )

-                return;

-            listener.onSelect(this);

-        }

-

-        public boolean isWritable() {

-            return key.isWritable();

-        }

-

-        public boolean isReadable() {

-            return key.isReadable();

-        }

-    }

-

-    public synchronized static SocketChannelAsyncChannelSelection register(

-            SocketChannel socketChannel, SelectorManagerListener listener)

-            throws IOException {

-

-        NIOAsyncChannelSelectorManager manager = null;

-        synchronized (freeManagers) {

-            if (freeManagers.size() > 0)

-                manager = (NIOAsyncChannelSelectorManager) freeManagers.getFirst();

-            if (manager == null) {

-                manager = new NIOAsyncChannelSelectorManager();

-                freeManagers.addFirst(manager);

-            }

-

-            // That manager may have filled up.

-            SocketChannelAsyncChannelSelection selection = manager.new SocketChannelAsyncChannelSelection(

-                    socketChannel, listener);

-            if (manager.useCounter >= MAX_CHANNELS_PER_SELECTOR) {

-                freeManagers.removeFirst();

-                fullManagers.addLast(manager);

-            }

-            return selection;

-        }

-    }

-

-    public synchronized static void setSelectorExecutor(Executor executor) {

-        NIOAsyncChannelSelectorManager.selectorExecutor = executor;

-    }

-    

-    public synchronized static void setChannelExecutor(Executor executor) {

-        NIOAsyncChannelSelectorManager.channelExecutor = executor;

-    }

-

-    private class SelectorWorker implements Runnable {

-                

-        public void run() {            

-            

-            String origName = Thread.currentThread().getName();

-            try {

-               Thread.currentThread().setName("Selector Worker: "+getId());

-               while ( isRunning() ) {

-

-                   int count = selector.select(10);

-                   if (count == 0)

-                       continue;                

-                    if( !isRunning() )

-                        return;

-

-                    // Get a java.util.Set containing the SelectionKey objects

-                    // for all channels that are ready for I/O.

-                    Set keys = selector.selectedKeys();

-    

-                    for (Iterator i = keys.iterator(); i.hasNext();) {                        

-                        final SelectionKey key = (SelectionKey) i.next();

-                        i.remove();

-

-                        if( !key.isValid() ) 

-                            continue;

-                        

-                        final SocketChannelAsyncChannelSelection s = (SocketChannelAsyncChannelSelection) key.attachment();

-                        s.disable();

-                        

-                        // Kick off another thread to find newly selected keys while we process the 

-                        // currently selected keys                

-                        channelExecutor.execute(new Runnable() {

-                            public void run() {

-                                try {

-                                    s.onSelect();

-                                    s.enable();

-                                } catch ( Throwable e ) {

-                                    System.err.println("ActiveIO unexpected error: ");

-                                    e.printStackTrace(System.err);

-                                }

-                            }

-                        });

-                    }

-                    

-               }

-            } catch (Throwable e) {

-                System.err.println("Unexpected exception: " + e);

-                e.printStackTrace();

-            } finally {

-                Thread.currentThread().setName(origName);

-            }

-        }

-    }

-

-    /**

-     * The selector used to wait for non-blocking events.

-     */

-    private Selector selector;

-

-    /**

-     * How many SelectionKeys does the selector have active.

-     */

-    private int useCounter;

-    private int id = getNextId();

-    private static int nextId;

-

-    private NIOAsyncChannelSelectorManager() throws IOException {

-        selector = Selector.open();

-    }

-    

-    synchronized private static int getNextId() {

-        return nextId++;

-    }

-

-    private int getId() {

-        return id ;

-    }

-

-    synchronized private void incrementUseCounter() {

-        useCounter++;

-        if (useCounter == 1) {

-            selectorExecutor.execute(new SelectorWorker());

-        }

-    }

-

-    synchronized private void decrementUseCounter() {

-        useCounter--;

-	 	synchronized(freeManagers) {	   	 		 

- 	 		 if( useCounter == 0 ) {

-  	 		 	freeManagers.remove(this);

-  	 		 }    	 		 

- 	 		 else if( useCounter < MAX_CHANNELS_PER_SELECTOR ) {

-  	 		 	fullManagers.remove(this);

-  	 		 	freeManagers.addLast(this);

-  	 		 }     	 		 

-	    }

-    }

-

-    synchronized private boolean isRunning() {

-        return useCounter > 0;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.nio;
+
+import edu.emory.mathcs.backport.java.util.concurrent.Executor;
+import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;
+
+import org.apache.activeio.ChannelFactory;
+
+import java.io.IOException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.SocketChannel;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Set;
+
+/**
+ * The SelectorManager will manage one Selector and the thread that checks the
+ * selector.
+ * 
+ * We may need to consider running more than one thread to check the selector if
+ * servicing the selector takes too long.
+ * 
+ * @version $Rev: 46019 $ $Date: 2004-09-14 05:56:06 -0400 (Tue, 14 Sep 2004) $
+ */
+final public class NIOAsyncChannelSelectorManager {
+
+    static private Executor selectorExecutor = ChannelFactory.DEFAULT_EXECUTOR;
+    static private Executor channelExecutor = ChannelFactory.DEFAULT_EXECUTOR;
+    
+    static private LinkedList freeManagers = new LinkedList();
+    static private LinkedList fullManagers = new LinkedList();
+    private static final int MAX_CHANNELS_PER_SELECTOR  = 50;
+    
+    static {
+       String os = System.getProperty("os.name");
+       if( os.startsWith("Linux") ) {
+           channelExecutor = new ScheduledThreadPoolExecutor(1);
+       }
+    } 
+
+    public static interface SelectorManagerListener {
+        public void onSelect(SocketChannelAsyncChannelSelection selector);
+    }
+
+    final public class SocketChannelAsyncChannelSelection {
+        
+        private final SelectionKey key;
+        private final SelectorManagerListener listener;
+        private boolean closed;
+        private int interest;
+
+        private SocketChannelAsyncChannelSelection(SocketChannel socketChannel, SelectorManagerListener listener)
+                throws ClosedChannelException {
+            this.listener = listener;
+            this.key = socketChannel.register(selector, 0, this);
+            incrementUseCounter();
+        }
+
+        public void setInterestOps(int ops) {
+            	if( closed ) 
+            		return;
+            	interest = ops;
+             enable();
+        }
+        
+        public void enable() {
+            if( closed ) 
+                return;
+            key.interestOps(interest);
+            selector.wakeup();
+        }
+
+        public void disable() {
+            if( closed ) 
+                return;
+            key.interestOps(0);
+        }
+
+        public void close() {
+        	if( closed ) 
+        		return;
+        	
+            key.cancel();
+            decrementUseCounter();
+            selector.wakeup();
+            closed=true;
+        }
+        
+        public void onSelect() {
+            if( !key.isValid() )
+                return;
+            listener.onSelect(this);
+        }
+
+        public boolean isWritable() {
+            return key.isWritable();
+        }
+
+        public boolean isReadable() {
+            return key.isReadable();
+        }
+    }
+
+    public synchronized static SocketChannelAsyncChannelSelection register(
+            SocketChannel socketChannel, SelectorManagerListener listener)
+            throws IOException {
+
+        NIOAsyncChannelSelectorManager manager = null;
+        synchronized (freeManagers) {
+            if (freeManagers.size() > 0)
+                manager = (NIOAsyncChannelSelectorManager) freeManagers.getFirst();
+            if (manager == null) {
+                manager = new NIOAsyncChannelSelectorManager();
+                freeManagers.addFirst(manager);
+            }
+
+            // That manager may have filled up.
+            SocketChannelAsyncChannelSelection selection = manager.new SocketChannelAsyncChannelSelection(
+                    socketChannel, listener);
+            if (manager.useCounter >= MAX_CHANNELS_PER_SELECTOR) {
+                freeManagers.removeFirst();
+                fullManagers.addLast(manager);
+            }
+            return selection;
+        }
+    }
+
+    public synchronized static void setSelectorExecutor(Executor executor) {
+        NIOAsyncChannelSelectorManager.selectorExecutor = executor;
+    }
+    
+    public synchronized static void setChannelExecutor(Executor executor) {
+        NIOAsyncChannelSelectorManager.channelExecutor = executor;
+    }
+
+    private class SelectorWorker implements Runnable {
+                
+        public void run() {            
+            
+            String origName = Thread.currentThread().getName();
+            try {
+               Thread.currentThread().setName("Selector Worker: "+getId());
+               while ( isRunning() ) {
+
+                   int count = selector.select(10);
+                   if (count == 0)
+                       continue;                
+                    if( !isRunning() )
+                        return;
+
+                    // Get a java.util.Set containing the SelectionKey objects
+                    // for all channels that are ready for I/O.
+                    Set keys = selector.selectedKeys();
+    
+                    for (Iterator i = keys.iterator(); i.hasNext();) {                        
+                        final SelectionKey key = (SelectionKey) i.next();
+                        i.remove();
+
+                        if( !key.isValid() ) 
+                            continue;
+                        
+                        final SocketChannelAsyncChannelSelection s = (SocketChannelAsyncChannelSelection) key.attachment();
+                        s.disable();
+                        
+                        // Kick off another thread to find newly selected keys while we process the 
+                        // currently selected keys                
+                        channelExecutor.execute(new Runnable() {
+                            public void run() {
+                                try {
+                                    s.onSelect();
+                                    s.enable();
+                                } catch ( Throwable e ) {
+                                    System.err.println("ActiveIO unexpected error: ");
+                                    e.printStackTrace(System.err);
+                                }
+                            }
+                        });
+                    }
+                    
+               }
+            } catch (Throwable e) {
+                System.err.println("Unexpected exception: " + e);
+                e.printStackTrace();
+            } finally {
+                Thread.currentThread().setName(origName);
+            }
+        }
+    }
+
+    /**
+     * The selector used to wait for non-blocking events.
+     */
+    private Selector selector;
+
+    /**
+     * How many SelectionKeys does the selector have active.
+     */
+    private int useCounter;
+    private int id = getNextId();
+    private static int nextId;
+
+    private NIOAsyncChannelSelectorManager() throws IOException {
+        selector = Selector.open();
+    }
+    
+    synchronized private static int getNextId() {
+        return nextId++;
+    }
+
+    private int getId() {
+        return id ;
+    }
+
+    synchronized private void incrementUseCounter() {
+        useCounter++;
+        if (useCounter == 1) {
+            selectorExecutor.execute(new SelectorWorker());
+        }
+    }
+
+    synchronized private void decrementUseCounter() {
+        useCounter--;
+	 	synchronized(freeManagers) {	   	 		 
+ 	 		 if( useCounter == 0 ) {
+  	 		 	freeManagers.remove(this);
+  	 		 }    	 		 
+ 	 		 else if( useCounter < MAX_CHANNELS_PER_SELECTOR ) {
+  	 		 	fullManagers.remove(this);
+  	 		 	freeManagers.addLast(this);
+  	 		 }     	 		 
+	    }
+    }
+
+    synchronized private boolean isRunning() {
+        return useCounter > 0;
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelServer.java
index 7dcee5d..2d3cead 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelServer.java
@@ -1,55 +1,55 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.nio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.nio.channels.ServerSocketChannel;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelServer;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannel;

-

-/**

- * A SynchChannelServer that creates

- * {@see org.apache.activeio.net.TcpSynchChannel}objects from accepted

- * tcp socket connections.

- * 

- * @version $Revision$

- */

-public class NIOAsyncChannelServer extends SocketSyncChannelServer {

-

-    private final boolean createWriteBufferedChannels;

-	private final boolean useDirectBuffers;

-

-    public NIOAsyncChannelServer(ServerSocketChannel socketChannel, URI bindURI, URI connectURI, boolean createWriteBufferedChannels, boolean useDirectBuffers) {

-        super(socketChannel.socket(), bindURI, connectURI);

-        this.createWriteBufferedChannels = createWriteBufferedChannels;

-		this.useDirectBuffers = useDirectBuffers;

-    }

-    

-    protected Channel createChannel(SocketStreamChannel c) throws IOException {

-        AsyncChannel channel = new NIOAsyncChannel(c.getSocket().getChannel(), useDirectBuffers);

-        if( createWriteBufferedChannels ) {

-            channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers), false);

-        }

-        return channel;

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.nio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.channels.ServerSocketChannel;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.filter.WriteBufferedAsyncChannel;
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelServer;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannel;
+
+/**
+ * A SynchChannelServer that creates
+ * {@see org.apache.activeio.net.TcpSynchChannel}objects from accepted
+ * tcp socket connections.
+ * 
+ * @version $Revision$
+ */
+public class NIOAsyncChannelServer extends SocketSyncChannelServer {
+
+    private final boolean createWriteBufferedChannels;
+	private final boolean useDirectBuffers;
+
+    public NIOAsyncChannelServer(ServerSocketChannel socketChannel, URI bindURI, URI connectURI, boolean createWriteBufferedChannels, boolean useDirectBuffers) {
+        super(socketChannel.socket(), bindURI, connectURI);
+        this.createWriteBufferedChannels = createWriteBufferedChannels;
+		this.useDirectBuffers = useDirectBuffers;
+    }
+    
+    protected Channel createChannel(SocketStreamChannel c) throws IOException {
+        AsyncChannel channel = new NIOAsyncChannel(c.getSocket().getChannel(), useDirectBuffers);
+        if( createWriteBufferedChannels ) {
+            channel = new WriteBufferedAsyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers), false);
+        }
+        return channel;
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelFactory.java
index 686fa94..b6ff6c1 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelFactory.java
@@ -1,252 +1,252 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.vmpipe;

-

-import java.io.IOException;

-import java.lang.reflect.InvocationHandler;

-import java.lang.reflect.InvocationTargetException;

-import java.lang.reflect.Method;

-import java.lang.reflect.Proxy;

-import java.net.URI;

-import java.util.Collections;

-import java.util.HashMap;

-import java.util.Map;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannelListener;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-

-/**

- * 

- * @version $Revision$

- */

-final public class VMPipeAsyncChannelFactory implements AsyncChannelFactory {

-    

-    //

-    // We do all this crazy stuff of looking the server map using System

-    // properties

-    // because this class could be loaded multiple times in different

-    // classloaders.

-    //

-    private static final String SERVER_MAP_LOCATION = VMPipeAsyncChannelFactory.class.getName() + ".SERVER_MAP";

-

-    private static final Map SERVER_MAP;

-    static {

-        Map m = null;

-        m = (Map) System.getProperties().get(SERVER_MAP_LOCATION);

-        if (m == null) {

-            m = Collections.synchronizedMap(new HashMap());

-            System.getProperties().put(SERVER_MAP_LOCATION, m);

-        }

-        SERVER_MAP = m;

-    }

-

-    private final static ClassLoader MY_CLASSLOADER = Packet.class.getClassLoader();

-    

-    

-    /**

-     * Used to marshal calls to a PipeChannel in a different classloader.

-     */

-    static public class ClassloaderAsyncChannelAdapter implements AsyncChannel {

-

-        private final ClassLoader cl;

-        private final Object channel;

-        private final Method writeMethod;

-        private final Method setListenerMethod;

-        private final Class listenerClazz;

-        private final Class packetClazz;

-        private final Object listenerProxy;

-        private final Method duplicateMethod;

-        private final Method startMethod;

-        private final Method stopMethod;

-        private final Method disposeMethod;

-

-        private AsyncChannelListener channelListener;

-

-        public class ListenerProxyHandler implements InvocationHandler {

-            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

-                switch (method.getName().length()) {

-                case 8: // onPacket

-                    Object packet = duplicateMethod.invoke(args[0], new Object[]{MY_CLASSLOADER});  

-                    channelListener.onPacket((Packet) packet);

-                    break;

-                case 13: // onPacketError

-                    channelListener.onPacketError((IOException) args[0]);

-                    break;

-                default:

-                    channelListener.onPacketError(new IOException("Unknown proxy method invocation: "+method.getName()));

-                }

-                return null;

-            }

-        }

-

-        public ClassloaderAsyncChannelAdapter(Object channel) throws SecurityException, NoSuchMethodException,

-                ClassNotFoundException {

-            this.channel = channel;

-            Class clazz = channel.getClass();

-            cl = clazz.getClassLoader();

-

-            listenerClazz = cl.loadClass(AsyncChannelListener.class.getName());

-            packetClazz = cl.loadClass(Packet.class.getName());

-            writeMethod = clazz.getMethod("write", new Class[] { packetClazz });

-            startMethod = clazz.getMethod("start", new Class[] { });

-            stopMethod = clazz.getMethod("stop", new Class[] {});

-            disposeMethod = clazz.getMethod("dispose", new Class[] { });

-

-            setListenerMethod = clazz.getMethod("setAsyncChannelListener", new Class[] { listenerClazz });

-            duplicateMethod = packetClazz.getMethod("duplicate", new Class[] { ClassLoader.class });

-

-            ListenerProxyHandler handler = new ListenerProxyHandler();

-            listenerProxy = Proxy.newProxyInstance(cl, new Class[] { listenerClazz }, handler);

-        }

-

-        public void write(Packet packet) throws IOException {

-            callIOExceptionMethod(writeMethod, new Object[] { packet.duplicate(cl) });

-        }

-

-        public void setAsyncChannelListener(AsyncChannelListener channelListener) {

-            this.channelListener = channelListener;

-            callMethod(setListenerMethod, new Object[] { channelListener == null ? null : listenerProxy });

-        }

-

-        public AsyncChannelListener getAsyncChannelListener() {

-            return channelListener;

-        }

-

-        public void dispose() {

-            callMethod(disposeMethod, new Object[] { });

-        }

-

-        public void start() throws IOException {

-            callIOExceptionMethod(startMethod, new Object[] {});

-        }

-

-        public void stop() throws IOException {

-            callIOExceptionMethod(stopMethod, new Object[] {});

-        }

-        

-        private void callMethod(Method method, Object[] args) {

-            try {

-                method.invoke(channel, args);

-            } catch (InvocationTargetException e) {

-                if (e.getTargetException() instanceof RuntimeException) {

-                    throw (RuntimeException) e.getTargetException();

-                }

-                throw new RuntimeException(e.getTargetException());

-            } catch (Throwable e) {

-                throw new RuntimeException("Reflexive invocation failed: " + e, e);

-            }            

-        }

-        

-        private void callIOExceptionMethod(Method method, Object[] args) throws IOException {

-            try {

-                method.invoke(channel, args);

-            } catch (InvocationTargetException e) {

-                if (e.getTargetException() instanceof IOException) {

-                    throw (IOException) e.getTargetException();

-                }

-                if (e.getTargetException() instanceof RuntimeException) {

-                    throw (RuntimeException) e.getTargetException();

-                }

-                throw new RuntimeException(e.getTargetException());

-            } catch (Throwable e) {

-                throw (IOException) new IOException("Reflexive invocation failed: " + e).initCause(e);

-            }            

-        }

-

-        //

-        // The following methods do not need to delegate since they

-        // are implemented as noops in the PipeChannel

-        //

-        public Object getAdapter(Class target) {

-            if (target.isAssignableFrom(getClass())) {

-                return this;

-            }

-            return null;

-        }

-

-        public void flush() throws IOException {

-        }

-

-    }

-

-    private boolean forceRefelection;

-

-    public AsyncChannel openAsyncChannel(URI location) throws IOException {

-

-        Object server = lookupServer(location);

-        if (!forceRefelection && server.getClass() == VMPipeAsyncChannelServer.class) {

-            return ((VMPipeAsyncChannelServer) server).connect();

-        }

-

-        // Asume server is in a different classloader.

-        // Use reflection to connect.

-        try {

-            Method method = server.getClass().getMethod("connect", new Class[] {});

-            Object channel = method.invoke(server, new Object[] {});

-            return new ClassloaderAsyncChannelAdapter(channel);

-        } catch (Throwable e) {

-            throw (IOException) new IOException("Connection could not be established: " + e).initCause(e);

-        }

-    }

-

-    public AsyncChannelServer bindAsyncChannel(URI bindURI) throws IOException {

-        VMPipeAsyncChannelServer server = new VMPipeAsyncChannelServer(bindURI);

-        bindServer(bindURI, server);

-        return server;

-    }

-

-    private static Map getServerMap() {

-        return SERVER_MAP;

-    }

-

-    static public String getServerKeyForURI(URI location) {

-        return location.getHost();

-    }

-

-    public static void bindServer(URI bindURI, VMPipeAsyncChannelServer server) throws IOException {

-        String key = getServerKeyForURI(bindURI);

-        if (getServerMap().get(key) != null)

-            throw new IOException("Server is allready bound at: " + bindURI);

-        getServerMap().put(key, server);

-    }

-

-    public static Object lookupServer(URI location) throws IOException {

-        String key = getServerKeyForURI(location);

-        Object server = getServerMap().get(key);

-        if (server == null) {

-            throw new IOException("Connection refused.");

-        }

-        return server;

-    }

-

-    public static void unbindServer(URI bindURI) {

-        String key = getServerKeyForURI(bindURI);

-        getServerMap().remove(key);

-    }

-

-    public boolean isForceRefelection() {

-        return forceRefelection;

-    }

-    

-    public void setForceRefelection(boolean forceRefelection) {

-        this.forceRefelection = forceRefelection;

-    }

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.vmpipe;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.URI;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannelListener;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+
+/**
+ * 
+ * @version $Revision$
+ */
+final public class VMPipeAsyncChannelFactory implements AsyncChannelFactory {
+    
+    //
+    // We do all this crazy stuff of looking the server map using System
+    // properties
+    // because this class could be loaded multiple times in different
+    // classloaders.
+    //
+    private static final String SERVER_MAP_LOCATION = VMPipeAsyncChannelFactory.class.getName() + ".SERVER_MAP";
+
+    private static final Map SERVER_MAP;
+    static {
+        Map m = null;
+        m = (Map) System.getProperties().get(SERVER_MAP_LOCATION);
+        if (m == null) {
+            m = Collections.synchronizedMap(new HashMap());
+            System.getProperties().put(SERVER_MAP_LOCATION, m);
+        }
+        SERVER_MAP = m;
+    }
+
+    private final static ClassLoader MY_CLASSLOADER = Packet.class.getClassLoader();
+    
+    
+    /**
+     * Used to marshal calls to a PipeChannel in a different classloader.
+     */
+    static public class ClassloaderAsyncChannelAdapter implements AsyncChannel {
+
+        private final ClassLoader cl;
+        private final Object channel;
+        private final Method writeMethod;
+        private final Method setListenerMethod;
+        private final Class listenerClazz;
+        private final Class packetClazz;
+        private final Object listenerProxy;
+        private final Method duplicateMethod;
+        private final Method startMethod;
+        private final Method stopMethod;
+        private final Method disposeMethod;
+
+        private AsyncChannelListener channelListener;
+
+        public class ListenerProxyHandler implements InvocationHandler {
+            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+                switch (method.getName().length()) {
+                case 8: // onPacket
+                    Object packet = duplicateMethod.invoke(args[0], new Object[]{MY_CLASSLOADER});  
+                    channelListener.onPacket((Packet) packet);
+                    break;
+                case 13: // onPacketError
+                    channelListener.onPacketError((IOException) args[0]);
+                    break;
+                default:
+                    channelListener.onPacketError(new IOException("Unknown proxy method invocation: "+method.getName()));
+                }
+                return null;
+            }
+        }
+
+        public ClassloaderAsyncChannelAdapter(Object channel) throws SecurityException, NoSuchMethodException,
+                ClassNotFoundException {
+            this.channel = channel;
+            Class clazz = channel.getClass();
+            cl = clazz.getClassLoader();
+
+            listenerClazz = cl.loadClass(AsyncChannelListener.class.getName());
+            packetClazz = cl.loadClass(Packet.class.getName());
+            writeMethod = clazz.getMethod("write", new Class[] { packetClazz });
+            startMethod = clazz.getMethod("start", new Class[] { });
+            stopMethod = clazz.getMethod("stop", new Class[] {});
+            disposeMethod = clazz.getMethod("dispose", new Class[] { });
+
+            setListenerMethod = clazz.getMethod("setAsyncChannelListener", new Class[] { listenerClazz });
+            duplicateMethod = packetClazz.getMethod("duplicate", new Class[] { ClassLoader.class });
+
+            ListenerProxyHandler handler = new ListenerProxyHandler();
+            listenerProxy = Proxy.newProxyInstance(cl, new Class[] { listenerClazz }, handler);
+        }
+
+        public void write(Packet packet) throws IOException {
+            callIOExceptionMethod(writeMethod, new Object[] { packet.duplicate(cl) });
+        }
+
+        public void setAsyncChannelListener(AsyncChannelListener channelListener) {
+            this.channelListener = channelListener;
+            callMethod(setListenerMethod, new Object[] { channelListener == null ? null : listenerProxy });
+        }
+
+        public AsyncChannelListener getAsyncChannelListener() {
+            return channelListener;
+        }
+
+        public void dispose() {
+            callMethod(disposeMethod, new Object[] { });
+        }
+
+        public void start() throws IOException {
+            callIOExceptionMethod(startMethod, new Object[] {});
+        }
+
+        public void stop() throws IOException {
+            callIOExceptionMethod(stopMethod, new Object[] {});
+        }
+        
+        private void callMethod(Method method, Object[] args) {
+            try {
+                method.invoke(channel, args);
+            } catch (InvocationTargetException e) {
+                if (e.getTargetException() instanceof RuntimeException) {
+                    throw (RuntimeException) e.getTargetException();
+                }
+                throw new RuntimeException(e.getTargetException());
+            } catch (Throwable e) {
+                throw new RuntimeException("Reflexive invocation failed: " + e, e);
+            }            
+        }
+        
+        private void callIOExceptionMethod(Method method, Object[] args) throws IOException {
+            try {
+                method.invoke(channel, args);
+            } catch (InvocationTargetException e) {
+                if (e.getTargetException() instanceof IOException) {
+                    throw (IOException) e.getTargetException();
+                }
+                if (e.getTargetException() instanceof RuntimeException) {
+                    throw (RuntimeException) e.getTargetException();
+                }
+                throw new RuntimeException(e.getTargetException());
+            } catch (Throwable e) {
+                throw (IOException) new IOException("Reflexive invocation failed: " + e).initCause(e);
+            }            
+        }
+
+        //
+        // The following methods do not need to delegate since they
+        // are implemented as noops in the PipeChannel
+        //
+        public Object getAdapter(Class target) {
+            if (target.isAssignableFrom(getClass())) {
+                return this;
+            }
+            return null;
+        }
+
+        public void flush() throws IOException {
+        }
+
+    }
+
+    private boolean forceRefelection;
+
+    public AsyncChannel openAsyncChannel(URI location) throws IOException {
+
+        Object server = lookupServer(location);
+        if (!forceRefelection && server.getClass() == VMPipeAsyncChannelServer.class) {
+            return ((VMPipeAsyncChannelServer) server).connect();
+        }
+
+        // Asume server is in a different classloader.
+        // Use reflection to connect.
+        try {
+            Method method = server.getClass().getMethod("connect", new Class[] {});
+            Object channel = method.invoke(server, new Object[] {});
+            return new ClassloaderAsyncChannelAdapter(channel);
+        } catch (Throwable e) {
+            throw (IOException) new IOException("Connection could not be established: " + e).initCause(e);
+        }
+    }
+
+    public AsyncChannelServer bindAsyncChannel(URI bindURI) throws IOException {
+        VMPipeAsyncChannelServer server = new VMPipeAsyncChannelServer(bindURI);
+        bindServer(bindURI, server);
+        return server;
+    }
+
+    private static Map getServerMap() {
+        return SERVER_MAP;
+    }
+
+    static public String getServerKeyForURI(URI location) {
+        return location.getHost();
+    }
+
+    public static void bindServer(URI bindURI, VMPipeAsyncChannelServer server) throws IOException {
+        String key = getServerKeyForURI(bindURI);
+        if (getServerMap().get(key) != null)
+            throw new IOException("Server is allready bound at: " + bindURI);
+        getServerMap().put(key, server);
+    }
+
+    public static Object lookupServer(URI location) throws IOException {
+        String key = getServerKeyForURI(location);
+        Object server = getServerMap().get(key);
+        if (server == null) {
+            throw new IOException("Connection refused.");
+        }
+        return server;
+    }
+
+    public static void unbindServer(URI bindURI) {
+        String key = getServerKeyForURI(bindURI);
+        getServerMap().remove(key);
+    }
+
+    public boolean isForceRefelection() {
+        return forceRefelection;
+    }
+    
+    public void setForceRefelection(boolean forceRefelection) {
+        this.forceRefelection = forceRefelection;
+    }
+    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelPipe.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelPipe.java
index e1a3405..412a540 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelPipe.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelPipe.java
@@ -1,163 +1,163 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.vmpipe;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelListener;

-

-import edu.emory.mathcs.backport.java.util.concurrent.Semaphore;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- * Used to connect the bottom ends of two Async channel stacks.

- * 

- */

-final public class VMPipeAsyncChannelPipe {

-

-    final PipeChannel leftChannel = new PipeChannel();

-    final PipeChannel rightChannel = new PipeChannel();

-

-    final public static class PipeChannel implements AsyncChannel {        

-        

-        private PipeChannel sibiling;        

-        private AsyncChannelListener channelListener;

-        private final Semaphore runMutext = new Semaphore(0);

-        private boolean disposed;

-        private boolean running;

-        

-        public PipeChannel() {

-        }

-        

-        public void setAsyncChannelListener(AsyncChannelListener channelListener) {

-            this.channelListener = channelListener;

-        }

-        public AsyncChannelListener getAsyncChannelListener() {

-            return channelListener;

-        }

-        

-        public void write(Packet packet) throws IOException {

-            if( disposed )

-                throw new IOException("Conneciton closed.");

-            sibiling.onPacket(packet, WAIT_FOREVER_TIMEOUT);

-        }

-

-        private void onPacket(Packet packet, long timeout) throws IOException {

-            try {

-                if( timeout == NO_WAIT_TIMEOUT ) {

-                    if( !runMutext.tryAcquire(0, TimeUnit.MILLISECONDS) )

-                        return;

-                } else if( timeout == WAIT_FOREVER_TIMEOUT ) {

-                    runMutext.acquire();

-                } else {

-                    if( !runMutext.tryAcquire(timeout, TimeUnit.MILLISECONDS) ) 

-                        return;

-                }

-            } catch (InterruptedException e) {

-                throw new InterruptedIOException();

-            }

-            try {

-                if( disposed ) {

-                    throw new IOException("Peer connection closed.");

-                }            

-                channelListener.onPacket(packet);

-            } finally {

-                runMutext.release();

-            }

-        }

-

-        public void flush() throws IOException {

-        }

-        

-        public void start() throws IOException {

-            if(running)

-                return;

-            if( channelListener==null )

-                throw new IOException("channelListener has not been set.");

-            running=true;

-            runMutext.release();

-        }

-        

-        public void stop() throws IOException {

-            if(!running)

-                return;            

-            try {

-                runMutext.tryAcquire(5, TimeUnit.SECONDS); 

-                running=false;

-            } catch (InterruptedException e) {

-                throw new InterruptedIOException();

-            }

-        }

-        

-        public void dispose() {

-            if( disposed )

-                return;

-            

-            if( running && channelListener!=null ) {

-                this.channelListener.onPacketError(new IOException("Pipe closed."));

-                running=false;

-            }

-            disposed = true;

-            runMutext.release();

-            

-            try {

-                // Inform the peer of the End Of Stream if he's listening.

-                sibiling.onPacket(EOSPacket.EOS_PACKET, NO_WAIT_TIMEOUT);

-            } catch (IOException e) {

-            }

-        }

-        

-        public PipeChannel getSibiling() {

-            return sibiling;

-        }

-        public void setSibiling(PipeChannel sibiling) {

-            this.sibiling = sibiling;

-        }

-

-        public Object getAdapter(Class target) {

-            if( target.isAssignableFrom(getClass()) ) {

-                return this;

-            }

-            return null;

-        }

-        

-        public String getId() {

-            return "0x"+Integer.toHexString(System.identityHashCode(this));

-        }

-        

-        public String toString() {

-            return "Pipe Channel from "+getId()+" to "+sibiling.getId();

-        }        

-    }

-    

-    public VMPipeAsyncChannelPipe() {

-        leftChannel.setSibiling(rightChannel);

-        rightChannel.setSibiling(leftChannel);

-    }

-    

-    public AsyncChannel getLeftAsyncChannel() {

-        return leftChannel;

-    }

-

-    public AsyncChannel getRightAsyncChannel() {

-        return rightChannel;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.vmpipe;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelListener;
+
+import edu.emory.mathcs.backport.java.util.concurrent.Semaphore;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ * Used to connect the bottom ends of two Async channel stacks.
+ * 
+ */
+final public class VMPipeAsyncChannelPipe {
+
+    final PipeChannel leftChannel = new PipeChannel();
+    final PipeChannel rightChannel = new PipeChannel();
+
+    final public static class PipeChannel implements AsyncChannel {        
+        
+        private PipeChannel sibiling;        
+        private AsyncChannelListener channelListener;
+        private final Semaphore runMutext = new Semaphore(0);
+        private boolean disposed;
+        private boolean running;
+        
+        public PipeChannel() {
+        }
+        
+        public void setAsyncChannelListener(AsyncChannelListener channelListener) {
+            this.channelListener = channelListener;
+        }
+        public AsyncChannelListener getAsyncChannelListener() {
+            return channelListener;
+        }
+        
+        public void write(Packet packet) throws IOException {
+            if( disposed )
+                throw new IOException("Conneciton closed.");
+            sibiling.onPacket(packet, WAIT_FOREVER_TIMEOUT);
+        }
+
+        private void onPacket(Packet packet, long timeout) throws IOException {
+            try {
+                if( timeout == NO_WAIT_TIMEOUT ) {
+                    if( !runMutext.tryAcquire(0, TimeUnit.MILLISECONDS) )
+                        return;
+                } else if( timeout == WAIT_FOREVER_TIMEOUT ) {
+                    runMutext.acquire();
+                } else {
+                    if( !runMutext.tryAcquire(timeout, TimeUnit.MILLISECONDS) ) 
+                        return;
+                }
+            } catch (InterruptedException e) {
+                throw new InterruptedIOException();
+            }
+            try {
+                if( disposed ) {
+                    throw new IOException("Peer connection closed.");
+                }            
+                channelListener.onPacket(packet);
+            } finally {
+                runMutext.release();
+            }
+        }
+
+        public void flush() throws IOException {
+        }
+        
+        public void start() throws IOException {
+            if(running)
+                return;
+            if( channelListener==null )
+                throw new IOException("channelListener has not been set.");
+            running=true;
+            runMutext.release();
+        }
+        
+        public void stop() throws IOException {
+            if(!running)
+                return;            
+            try {
+                runMutext.tryAcquire(5, TimeUnit.SECONDS); 
+                running=false;
+            } catch (InterruptedException e) {
+                throw new InterruptedIOException();
+            }
+        }
+        
+        public void dispose() {
+            if( disposed )
+                return;
+            
+            if( running && channelListener!=null ) {
+                this.channelListener.onPacketError(new IOException("Pipe closed."));
+                running=false;
+            }
+            disposed = true;
+            runMutext.release();
+            
+            try {
+                // Inform the peer of the End Of Stream if he's listening.
+                sibiling.onPacket(EOSPacket.EOS_PACKET, NO_WAIT_TIMEOUT);
+            } catch (IOException e) {
+            }
+        }
+        
+        public PipeChannel getSibiling() {
+            return sibiling;
+        }
+        public void setSibiling(PipeChannel sibiling) {
+            this.sibiling = sibiling;
+        }
+
+        public Object getAdapter(Class target) {
+            if( target.isAssignableFrom(getClass()) ) {
+                return this;
+            }
+            return null;
+        }
+        
+        public String getId() {
+            return "0x"+Integer.toHexString(System.identityHashCode(this));
+        }
+        
+        public String toString() {
+            return "Pipe Channel from "+getId()+" to "+sibiling.getId();
+        }        
+    }
+    
+    public VMPipeAsyncChannelPipe() {
+        leftChannel.setSibiling(rightChannel);
+        rightChannel.setSibiling(leftChannel);
+    }
+    
+    public AsyncChannel getLeftAsyncChannel() {
+        return leftChannel;
+    }
+
+    public AsyncChannel getRightAsyncChannel() {
+        return rightChannel;
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelServer.java
index 193c2a1..9c6b71b 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelServer.java
@@ -1,85 +1,85 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.vmpipe;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-

-/**

- * @version $Revision$

- */

-final public class VMPipeAsyncChannelServer implements AsyncChannelServer {

-

-    private final URI bindURI;

-    private final URI connectURI;

-    private AcceptListener acceptListener;

-    private boolean disposed;

-    

-    public VMPipeAsyncChannelServer(URI bindURI) {

-        this.bindURI = this.connectURI = bindURI;

-    }

-

-    public URI getBindURI() {

-        return bindURI;

-    }

-

-    public URI getConnectURI() {

-        return this.connectURI;

-    }

-

-    public void dispose() {

-        if( disposed )

-            return;

-        

-        VMPipeAsyncChannelFactory.unbindServer(bindURI);

-        disposed=true;

-    }

-

-    public void start() throws IOException {

-        if( acceptListener==null )

-            throw new IOException("acceptListener has not been set.");

-    }

-

-    public void stop() {

-    }

-

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-    

-    public String toString() {

-        return "VM Pipe Server: "+getConnectURI();

-    }

-

-    public void setAcceptListener(AcceptListener acceptListener) {

-        this.acceptListener = acceptListener;

-    }

-

-    public AsyncChannel connect() {

-        VMPipeAsyncChannelPipe pipe = new VMPipeAsyncChannelPipe();

-        acceptListener.onAccept(pipe.getRightAsyncChannel());

-        return pipe.getLeftAsyncChannel();

-    }

-    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.vmpipe;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+
+/**
+ * @version $Revision$
+ */
+final public class VMPipeAsyncChannelServer implements AsyncChannelServer {
+
+    private final URI bindURI;
+    private final URI connectURI;
+    private AcceptListener acceptListener;
+    private boolean disposed;
+    
+    public VMPipeAsyncChannelServer(URI bindURI) {
+        this.bindURI = this.connectURI = bindURI;
+    }
+
+    public URI getBindURI() {
+        return bindURI;
+    }
+
+    public URI getConnectURI() {
+        return this.connectURI;
+    }
+
+    public void dispose() {
+        if( disposed )
+            return;
+        
+        VMPipeAsyncChannelFactory.unbindServer(bindURI);
+        disposed=true;
+    }
+
+    public void start() throws IOException {
+        if( acceptListener==null )
+            throw new IOException("acceptListener has not been set.");
+    }
+
+    public void stop() {
+    }
+
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+    
+    public String toString() {
+        return "VM Pipe Server: "+getConnectURI();
+    }
+
+    public void setAcceptListener(AcceptListener acceptListener) {
+        this.acceptListener = acceptListener;
+    }
+
+    public AsyncChannel connect() {
+        VMPipeAsyncChannelPipe pipe = new VMPipeAsyncChannelPipe();
+        acceptListener.onAccept(pipe.getRightAsyncChannel());
+        return pipe.getLeftAsyncChannel();
+    }
+    
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannel.java
index a950c49..b0b3500 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannel.java
@@ -1,98 +1,98 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.Packet;

-

-

-/**

- * A SynchChannelFilter can be used as a filter another {@see org.apache.activeio.SynchChannel}

- * Most {@see org.apache.activeio.SynchChannel} that are not directly accessing the network will 

- * extends the SynchChannelFilter since they act as a filter between the client and the network.

- *    

- * @version $Revision$

- */

-public class FilterSyncChannel implements SyncChannel {

-

-    private final SyncChannel next;

-

-    public FilterSyncChannel(SyncChannel next) {

-        this.next = next;

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)

-     */

-    public void write(Packet packet) throws IOException {

-        next.write(packet);

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#flush()

-     */

-    public void flush() throws IOException {

-        next.flush();

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        next.dispose();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#start()

-     */

-    public void start() throws IOException {

-        next.start();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#stop()

-     */

-    public void stop() throws IOException {

-        next.stop();

-    }

-

-    /**

-     * @return Returns the next.

-     */

-    public SyncChannel getNext() {

-        return next;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.sync.SyncChannel#read(long)

-     */

-    public Packet read(long timeout) throws IOException {

-        return next.read(timeout);

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return next.getAdapter(target);

-    }    

-    

-    public String toString() {

-        return next.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ * A SynchChannelFilter can be used as a filter another {@see org.apache.activeio.SynchChannel}
+ * Most {@see org.apache.activeio.SynchChannel} that are not directly accessing the network will 
+ * extends the SynchChannelFilter since they act as a filter between the client and the network.
+ *    
+ * @version $Revision$
+ */
+public class FilterSyncChannel implements SyncChannel {
+
+    private final SyncChannel next;
+
+    public FilterSyncChannel(SyncChannel next) {
+        this.next = next;
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)
+     */
+    public void write(Packet packet) throws IOException {
+        next.write(packet);
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#flush()
+     */
+    public void flush() throws IOException {
+        next.flush();
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        next.dispose();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#start()
+     */
+    public void start() throws IOException {
+        next.start();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#stop()
+     */
+    public void stop() throws IOException {
+        next.stop();
+    }
+
+    /**
+     * @return Returns the next.
+     */
+    public SyncChannel getNext() {
+        return next;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.sync.SyncChannel#read(long)
+     */
+    public Packet read(long timeout) throws IOException {
+        return next.read(timeout);
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return next.getAdapter(target);
+    }    
+    
+    public String toString() {
+        return next.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannelServer.java
index 0059cec..d7756f2 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/FilterSyncChannelServer.java
@@ -1,99 +1,99 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.Channel;

-

-

-/**

- * A SynchChannelFilter can be used as a filter another {@see org.apache.activeio.SynchChannel}

- * Most {@see org.apache.activeio.SynchChannel} that are not directly accessing the network will 

- * extends the SynchChannelFilter since they act as a filter between the client and the network.

- *    

- * @version $Revision$

- */

-public class FilterSyncChannelServer implements SyncChannelServer {

-

-    private final SyncChannelServer next;

-

-    public FilterSyncChannelServer(SyncChannelServer next) {

-        this.next = next;

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        next.dispose();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#start()

-     */

-    public void start() throws IOException {

-        next.start();

-    }

-

-    /**

-     * @see org.apache.activeio.Service#stop()

-     */

-    public void stop() throws IOException {

-        next.stop();

-    }

-

-    /**

-     * @return Returns the next.

-     */

-    public SyncChannelServer getNext() {

-        return next;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.sync.SyncChannelServer#accept(long)

-     */

-    public Channel accept(long timeout) throws IOException {

-        return next.accept(timeout);

-    }

-

-    /**

-     * @see org.apache.activeio.ChannelServer#getBindURI()

-     */

-    public URI getBindURI() {

-        return next.getBindURI();

-    }

-

-    /**

-     * @see org.apache.activeio.ChannelServer#getConnectURI()

-     */

-    public URI getConnectURI() {

-        return next.getConnectURI();

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return next.getAdapter(target);

-    }    

-

-    public String toString() {

-        return next.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.Channel;
+
+
+/**
+ * A SynchChannelFilter can be used as a filter another {@see org.apache.activeio.SynchChannel}
+ * Most {@see org.apache.activeio.SynchChannel} that are not directly accessing the network will 
+ * extends the SynchChannelFilter since they act as a filter between the client and the network.
+ *    
+ * @version $Revision$
+ */
+public class FilterSyncChannelServer implements SyncChannelServer {
+
+    private final SyncChannelServer next;
+
+    public FilterSyncChannelServer(SyncChannelServer next) {
+        this.next = next;
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        next.dispose();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#start()
+     */
+    public void start() throws IOException {
+        next.start();
+    }
+
+    /**
+     * @see org.apache.activeio.Service#stop()
+     */
+    public void stop() throws IOException {
+        next.stop();
+    }
+
+    /**
+     * @return Returns the next.
+     */
+    public SyncChannelServer getNext() {
+        return next;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.sync.SyncChannelServer#accept(long)
+     */
+    public Channel accept(long timeout) throws IOException {
+        return next.accept(timeout);
+    }
+
+    /**
+     * @see org.apache.activeio.ChannelServer#getBindURI()
+     */
+    public URI getBindURI() {
+        return next.getBindURI();
+    }
+
+    /**
+     * @see org.apache.activeio.ChannelServer#getConnectURI()
+     */
+    public URI getConnectURI() {
+        return next.getConnectURI();
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return next.getAdapter(target);
+    }    
+
+    public String toString() {
+        return next.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannel.java
index 7a6d4f1..d7272ec 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannel.java
@@ -1,59 +1,59 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.packet.sync;

-

-import java.io.IOException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.Packet;

-

-

-/**

- * SyncChannel objects allow threaded to synchronously block on the <code>receiveUpPacket</code>

- * method to get 'up' {@see org.apache.activeio.Packet} objects when they arrive.

- * 

- * @version $Revision$

- */

-public interface SyncChannel extends Channel {

-    

-    /**

-     * Used to synchronously receive a packet of information going 'up' the channel.

-     * This method blocks until a packet is received or the operation experiences timeout.

-     * 

-     * @param timeout

-     * @return the packet received or null if the timeout occurred.

-     * @throws IOException

-     */

-    Packet read(long timeout) throws IOException;

-    

-    /**

-     * Sends a packet down the channel towards the media.

-     * 

-     * @param packet

-     * @throws IOException

-     */

-    void write(Packet packet) throws IOException;

-

-    /**

-     * Some channels may buffer data which may be sent down if flush() is called.

-     * 

-     * @throws IOException

-     */

-    void flush() throws IOException;    

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.packet.sync;
+
+import java.io.IOException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ * SyncChannel objects allow threaded to synchronously block on the <code>receiveUpPacket</code>
+ * method to get 'up' {@see org.apache.activeio.Packet} objects when they arrive.
+ * 
+ * @version $Revision$
+ */
+public interface SyncChannel extends Channel {
+    
+    /**
+     * Used to synchronously receive a packet of information going 'up' the channel.
+     * This method blocks until a packet is received or the operation experiences timeout.
+     * 
+     * @param timeout
+     * @return the packet received or null if the timeout occurred.
+     * @throws IOException
+     */
+    Packet read(long timeout) throws IOException;
+    
+    /**
+     * Sends a packet down the channel towards the media.
+     * 
+     * @param packet
+     * @throws IOException
+     */
+    void write(Packet packet) throws IOException;
+
+    /**
+     * Some channels may buffer data which may be sent down if flush() is called.
+     * 
+     * @throws IOException
+     */
+    void flush() throws IOException;    
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelFactory.java
index 347393e..17bd9b9 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelFactory.java
@@ -1,46 +1,46 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync;

-

-import java.io.IOException;

-import java.net.URI;

-

-/**

- * SynchChannelFactory objects can create {@see org.apache.activeio.SynchChannel}

- * and {@see org.apache.activeio.SynchChannelServer} objects. 

- * 

- * @version $Revision$

- */

-public interface SyncChannelFactory {

-

-	/**

-     * Opens a connection to server.

-     * 

-     * @param location 

-     * @return

-     */

-	public SyncChannel openSyncChannel(URI location) throws IOException;

-	

-	/**

-     * Binds a server at the URI location.

-     * 

-     * @param location

-     * @return

-     */

-	public SyncChannelServer bindSyncChannel(URI location) throws IOException;

-	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync;
+
+import java.io.IOException;
+import java.net.URI;
+
+/**
+ * SynchChannelFactory objects can create {@see org.apache.activeio.SynchChannel}
+ * and {@see org.apache.activeio.SynchChannelServer} objects. 
+ * 
+ * @version $Revision$
+ */
+public interface SyncChannelFactory {
+
+	/**
+     * Opens a connection to server.
+     * 
+     * @param location 
+     * @return
+     */
+	public SyncChannel openSyncChannel(URI location) throws IOException;
+	
+	/**
+     * Binds a server at the URI location.
+     * 
+     * @param location
+     * @return
+     */
+	public SyncChannelServer bindSyncChannel(URI location) throws IOException;
+	
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelServer.java
index 26f7902..6b658c7 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/SyncChannelServer.java
@@ -1,39 +1,39 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync;

-

-import java.io.IOException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-

-

-

-/**

- * A SynchChannelServer object provides an <code>accept</code> method to synchronously 

- * accept and create {@see org.apache.activeio.Channel} objects.

- * 

- * @version $Revision$

- */

-public interface SyncChannelServer extends ChannelServer {

-

-    static final public long NO_WAIT_TIMEOUT=0;

-	static final public long WAIT_FOREVER_TIMEOUT=-1;	

-	

-	public Channel accept(long timeout) throws IOException;

-	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync;
+
+import java.io.IOException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+
+
+
+/**
+ * A SynchChannelServer object provides an <code>accept</code> method to synchronously 
+ * accept and create {@see org.apache.activeio.Channel} objects.
+ * 
+ * @version $Revision$
+ */
+public interface SyncChannelServer extends ChannelServer {
+
+    static final public long NO_WAIT_TIMEOUT=0;
+	static final public long WAIT_FOREVER_TIMEOUT=-1;	
+	
+	public Channel accept(long timeout) throws IOException;
+	
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramContext.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramContext.java
index c3be082..8d74079 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramContext.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramContext.java
@@ -1,56 +1,56 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.datagram;

-

-import java.net.DatagramPacket;

-import java.net.InetAddress;

-

-

-final public class DatagramContext {

-

-    public InetAddress address;

-    public Integer port;

-

-    public DatagramContext() {            

-    }

-    

-    public DatagramContext(DatagramPacket datagramPacket) {

-        this(datagramPacket.getAddress(), new Integer(datagramPacket.getPort()));

-    }

-    

-    public DatagramContext(InetAddress address, Integer port) {

-        this.address = address;

-        this.port = port;

-    }

-    

-    public InetAddress getAddress() {

-        return address;

-    }

-

-    public void setAddress(InetAddress address) {

-        this.address = address;

-    }

-

-    public Integer getPort() {

-        return port;

-    }

-

-    public void setPort(Integer port) {

-        this.port = port;

-    }

-    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.datagram;
+
+import java.net.DatagramPacket;
+import java.net.InetAddress;
+
+
+final public class DatagramContext {
+
+    public InetAddress address;
+    public Integer port;
+
+    public DatagramContext() {            
+    }
+    
+    public DatagramContext(DatagramPacket datagramPacket) {
+        this(datagramPacket.getAddress(), new Integer(datagramPacket.getPort()));
+    }
+    
+    public DatagramContext(InetAddress address, Integer port) {
+        this.address = address;
+        this.port = port;
+    }
+    
+    public InetAddress getAddress() {
+        return address;
+    }
+
+    public void setAddress(InetAddress address) {
+        this.address = address;
+    }
+
+    public Integer getPort() {
+        return port;
+    }
+
+    public void setPort(Integer port) {
+        this.port = port;
+    }
+    
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannel.java
index d08810c..6243026 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannel.java
@@ -1,165 +1,165 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.packet.sync.datagram;

-

-import java.io.IOException;

-import java.net.DatagramPacket;

-import java.net.DatagramSocket;

-import java.net.SocketException;

-import java.net.SocketTimeoutException;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.ByteSequence;

-import org.apache.activeio.packet.FilterPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-/**

- * A {@see org.apache.activeio.SynchChannel}implementation that uses

- * TCP to talk to the network.

- * 

- * @version $Revision$

- */

-public class DatagramSocketSyncChannel implements SyncChannel {

-

-    private final class UDPFilterPacket extends FilterPacket {

-        private final DatagramPacket packet;

-

-        private UDPFilterPacket(Packet next, DatagramPacket packet) {

-            super(next);

-            this.packet = packet;

-        }

-

-        public Object getAdapter(Class target) {

-            if( target == DatagramContext.class ) {

-                return new DatagramContext(packet);

-            }

-            return super.getAdapter(target);

-        }

-

-        public Packet filter(Packet packet) {

-            return new UDPFilterPacket(packet, this.packet);

-        }

-    }

-

-    private static final int DEFAULT_BUFFER_SIZE = 64 * 1024;

-

-    private final DatagramSocket socket;

-

-    private boolean disposed;

-

-    private int curentSoTimeout;

-

-    /**

-     * Construct basic helpers

-     * 

-     * @param wireFormat

-     * @throws IOException

-     */

-    protected DatagramSocketSyncChannel(DatagramSocket socket) throws IOException {

-        this.socket = socket;

-        socket.setReceiveBufferSize(DEFAULT_BUFFER_SIZE);

-        socket.setSendBufferSize(DEFAULT_BUFFER_SIZE);

-    }

-

-    protected DatagramSocket getSocket() {

-        return socket;

-    }

-

-    /**

-     * @see org.apache.activeio.packet.sync.SyncChannel#read(long)

-     */

-    public org.apache.activeio.packet.Packet read(long timeout) throws IOException {

-        try {

-

-            if (timeout == SyncChannelServer.WAIT_FOREVER_TIMEOUT)

-                setSoTimeout(0);

-            else if (timeout == SyncChannelServer.NO_WAIT_TIMEOUT)

-                setSoTimeout(1);

-            else

-                setSoTimeout((int) timeout);

-

-            // FYI: message data is truncated if biger than this buffer.

-            final byte data[] = new byte[DEFAULT_BUFFER_SIZE];

-            final DatagramPacket packet = new DatagramPacket(data, data.length);

-            socket.receive(packet);

-            

-            // A FilterPacket is used to provide the UdpDatagramContext via narrow.

-            return new UDPFilterPacket(new ByteArrayPacket(data, 0, packet.getLength()), packet);

-            

-        } catch (SocketTimeoutException e) {

-            return null;

-        }

-    }

-

-    private void setSoTimeout(int i) throws SocketException {

-        if (curentSoTimeout != i) {

-            socket.setSoTimeout(i);

-            curentSoTimeout = i;

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)

-     */

-    public void write(org.apache.activeio.packet.Packet packet) throws IOException {

-        ByteSequence sequence = packet.asByteSequence();

-

-        DatagramContext context = (DatagramContext) packet.getAdapter(DatagramContext.class);

-        if( context!=null ) {

-            socket.send(new DatagramPacket(sequence.getData(),sequence.getOffset(), sequence.getLength(), context.address, context.port.intValue()));

-        } else {

-            socket.send(new DatagramPacket(sequence.getData(),sequence.getOffset(), sequence.getLength()));

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#flush()

-     */

-    public void flush() throws IOException {

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        if (disposed)

-            return;

-        socket.close();

-        disposed = true;

-    }

-

-    public void start() throws IOException {

-    }

-

-    public void stop() throws IOException {

-    }

-

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-

-    public String toString() {

-        return "Datagram Connection: "+socket.getLocalSocketAddress()+" -> "+socket.getRemoteSocketAddress();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.packet.sync.datagram;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.ByteSequence;
+import org.apache.activeio.packet.FilterPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+/**
+ * A {@see org.apache.activeio.SynchChannel}implementation that uses
+ * TCP to talk to the network.
+ * 
+ * @version $Revision$
+ */
+public class DatagramSocketSyncChannel implements SyncChannel {
+
+    private final class UDPFilterPacket extends FilterPacket {
+        private final DatagramPacket packet;
+
+        private UDPFilterPacket(Packet next, DatagramPacket packet) {
+            super(next);
+            this.packet = packet;
+        }
+
+        public Object getAdapter(Class target) {
+            if( target == DatagramContext.class ) {
+                return new DatagramContext(packet);
+            }
+            return super.getAdapter(target);
+        }
+
+        public Packet filter(Packet packet) {
+            return new UDPFilterPacket(packet, this.packet);
+        }
+    }
+
+    private static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
+
+    private final DatagramSocket socket;
+
+    private boolean disposed;
+
+    private int curentSoTimeout;
+
+    /**
+     * Construct basic helpers
+     * 
+     * @param wireFormat
+     * @throws IOException
+     */
+    protected DatagramSocketSyncChannel(DatagramSocket socket) throws IOException {
+        this.socket = socket;
+        socket.setReceiveBufferSize(DEFAULT_BUFFER_SIZE);
+        socket.setSendBufferSize(DEFAULT_BUFFER_SIZE);
+    }
+
+    protected DatagramSocket getSocket() {
+        return socket;
+    }
+
+    /**
+     * @see org.apache.activeio.packet.sync.SyncChannel#read(long)
+     */
+    public org.apache.activeio.packet.Packet read(long timeout) throws IOException {
+        try {
+
+            if (timeout == SyncChannelServer.WAIT_FOREVER_TIMEOUT)
+                setSoTimeout(0);
+            else if (timeout == SyncChannelServer.NO_WAIT_TIMEOUT)
+                setSoTimeout(1);
+            else
+                setSoTimeout((int) timeout);
+
+            // FYI: message data is truncated if biger than this buffer.
+            final byte data[] = new byte[DEFAULT_BUFFER_SIZE];
+            final DatagramPacket packet = new DatagramPacket(data, data.length);
+            socket.receive(packet);
+            
+            // A FilterPacket is used to provide the UdpDatagramContext via narrow.
+            return new UDPFilterPacket(new ByteArrayPacket(data, 0, packet.getLength()), packet);
+            
+        } catch (SocketTimeoutException e) {
+            return null;
+        }
+    }
+
+    private void setSoTimeout(int i) throws SocketException {
+        if (curentSoTimeout != i) {
+            socket.setSoTimeout(i);
+            curentSoTimeout = i;
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)
+     */
+    public void write(org.apache.activeio.packet.Packet packet) throws IOException {
+        ByteSequence sequence = packet.asByteSequence();
+
+        DatagramContext context = (DatagramContext) packet.getAdapter(DatagramContext.class);
+        if( context!=null ) {
+            socket.send(new DatagramPacket(sequence.getData(),sequence.getOffset(), sequence.getLength(), context.address, context.port.intValue()));
+        } else {
+            socket.send(new DatagramPacket(sequence.getData(),sequence.getOffset(), sequence.getLength()));
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#flush()
+     */
+    public void flush() throws IOException {
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        if (disposed)
+            return;
+        socket.close();
+        disposed = true;
+    }
+
+    public void start() throws IOException {
+    }
+
+    public void stop() throws IOException {
+    }
+
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+
+    public String toString() {
+        return "Datagram Connection: "+socket.getLocalSocketAddress()+" -> "+socket.getRemoteSocketAddress();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannelFactory.java
index a03a034..7bb716c 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/datagram/DatagramSocketSyncChannelFactory.java
@@ -1,84 +1,84 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.datagram;

-

-import java.io.IOException;

-import java.net.DatagramSocket;

-import java.net.InetAddress;

-import java.net.URI;

-

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-/**

- * A TcpSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}

- * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects.

- * 

- * @version $Revision$

- */

-public class DatagramSocketSyncChannelFactory implements SyncChannelFactory {

-

-    /**

-     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.

-     * 

-     * @see org.apache.activeio.SynchChannelFactory#openSyncChannel(java.net.URI)

-     */

-    public SyncChannel openSyncChannel(URI location) throws IOException {

-        DatagramSocket socket=null;

-        socket = new DatagramSocket();

-        if( location != null ) {

-            InetAddress address = InetAddress.getByName(location.getHost());

-            socket.connect(address, location.getPort());

-        }

-        return createSyncChannel(socket);

-    }

-

-    /**

-     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.

-     * 

-     */

-    public SyncChannel openSyncChannel(URI location, URI localLocation) throws IOException {

-        DatagramSocket socket=null;

-        InetAddress address = InetAddress.getByName(localLocation.getHost());

-        socket = new DatagramSocket(localLocation.getPort(), address);

-

-        if( location != null ) {

-            address = InetAddress.getByName(location.getHost());

-            socket.connect(address, location.getPort());

-        }

-        return createSyncChannel(socket);

-    }

-

-    /**

-     * @param socket

-     * @return

-     * @throws IOException

-     */

-    protected SyncChannel createSyncChannel(DatagramSocket socket) throws IOException {

-        return new DatagramSocketSyncChannel(socket);

-    }

-

-    /**

-     * @throws IOException allways thrown.

-     * @see org.apache.activeio.SynchChannelFactory#bindSynchChannel(java.net.URI)

-     */

-    public SyncChannelServer bindSyncChannel(URI location) throws IOException {

-        throw new IOException("A SynchChannelServer is not available for this channel.");

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.datagram;
+
+import java.io.IOException;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.URI;
+
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+/**
+ * A TcpSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}
+ * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects.
+ * 
+ * @version $Revision$
+ */
+public class DatagramSocketSyncChannelFactory implements SyncChannelFactory {
+
+    /**
+     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
+     * 
+     * @see org.apache.activeio.SynchChannelFactory#openSyncChannel(java.net.URI)
+     */
+    public SyncChannel openSyncChannel(URI location) throws IOException {
+        DatagramSocket socket=null;
+        socket = new DatagramSocket();
+        if( location != null ) {
+            InetAddress address = InetAddress.getByName(location.getHost());
+            socket.connect(address, location.getPort());
+        }
+        return createSyncChannel(socket);
+    }
+
+    /**
+     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
+     * 
+     */
+    public SyncChannel openSyncChannel(URI location, URI localLocation) throws IOException {
+        DatagramSocket socket=null;
+        InetAddress address = InetAddress.getByName(localLocation.getHost());
+        socket = new DatagramSocket(localLocation.getPort(), address);
+
+        if( location != null ) {
+            address = InetAddress.getByName(location.getHost());
+            socket.connect(address, location.getPort());
+        }
+        return createSyncChannel(socket);
+    }
+
+    /**
+     * @param socket
+     * @return
+     * @throws IOException
+     */
+    protected SyncChannel createSyncChannel(DatagramSocket socket) throws IOException {
+        return new DatagramSocketSyncChannel(socket);
+    }
+
+    /**
+     * @throws IOException allways thrown.
+     * @see org.apache.activeio.SynchChannelFactory#bindSynchChannel(java.net.URI)
+     */
+    public SyncChannelServer bindSyncChannel(URI location) throws IOException {
+        throw new IOException("A SynchChannelServer is not available for this channel.");
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PacketAggregatingSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PacketAggregatingSyncChannel.java
index 53791bf..d2954ce 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PacketAggregatingSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PacketAggregatingSyncChannel.java
@@ -1,94 +1,94 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.filter;

-

-import java.io.IOException;

-import java.util.LinkedList;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.FilterSyncChannel;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.util.PacketAggregator;

-

-/**

- * This PacketAggregatingSynchChannel can be used when the client is sending a

- * 'record' style packet down the channel stack and needs receiving end to

- * receive the same 'record' packets.

- * 

- * This is very usefull since in general, a channel does not garantee that a

- * Packet that is sent down will not be fragmented or combined with other Packet

- * objects.

- * 

- * This {@see org.apache.activeio.SynchChannel} adds a 4 byte header

- * to each packet that is sent down.

- * 

- * @version $Revision$

- */

-final public class PacketAggregatingSyncChannel extends FilterSyncChannel {

-

-    private final LinkedList assembledPackets = new LinkedList();    

-    private final PacketAggregator aggregator = new PacketAggregator() {

-        protected void packetAssembled(Packet packet) {

-            assembledPackets.addLast(packet);

-        }

-    };

-    

-    /**

-     * @param next

-     */

-    public PacketAggregatingSyncChannel(SyncChannel next) {

-        super(next);

-    }

-    

-    public Packet read(long timeout) throws IOException {

-        long start = System.currentTimeMillis();

-        if( assembledPackets.isEmpty() ) {

-            while( true ) {

-                

-	            Packet packet = getNext().read(timeout);

-	            if( packet==null ) {

-                    return null;

-	            }

-	            

-	            aggregator.addRawPacket(packet);

-	            

-	            // Should we try to get more packets?

-	            if( assembledPackets.isEmpty() ) {

-	                if( timeout == WAIT_FOREVER_TIMEOUT )

-	                    continue;

-	                

-	                timeout = Math.max(0, timeout-(System.currentTimeMillis()-start));

-	                if( timeout != 0 )

-	                    continue;

-	                

-	                return null;

-	            } else {

-	                return (Packet) assembledPackets.removeFirst();

-	            }

-            }

-            

-        } else {

-            return (Packet) assembledPackets.removeFirst();

-        }

-        

-    }

-    

-    public void write(Packet packet) throws IOException {

-        getNext().write(aggregator.getHeader(packet));

-        getNext().write(packet);

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.filter;
+
+import java.io.IOException;
+import java.util.LinkedList;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.FilterSyncChannel;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.util.PacketAggregator;
+
+/**
+ * This PacketAggregatingSynchChannel can be used when the client is sending a
+ * 'record' style packet down the channel stack and needs receiving end to
+ * receive the same 'record' packets.
+ * 
+ * This is very usefull since in general, a channel does not garantee that a
+ * Packet that is sent down will not be fragmented or combined with other Packet
+ * objects.
+ * 
+ * This {@see org.apache.activeio.SynchChannel} adds a 4 byte header
+ * to each packet that is sent down.
+ * 
+ * @version $Revision$
+ */
+final public class PacketAggregatingSyncChannel extends FilterSyncChannel {
+
+    private final LinkedList assembledPackets = new LinkedList();    
+    private final PacketAggregator aggregator = new PacketAggregator() {
+        protected void packetAssembled(Packet packet) {
+            assembledPackets.addLast(packet);
+        }
+    };
+    
+    /**
+     * @param next
+     */
+    public PacketAggregatingSyncChannel(SyncChannel next) {
+        super(next);
+    }
+    
+    public Packet read(long timeout) throws IOException {
+        long start = System.currentTimeMillis();
+        if( assembledPackets.isEmpty() ) {
+            while( true ) {
+                
+	            Packet packet = getNext().read(timeout);
+	            if( packet==null ) {
+                    return null;
+	            }
+	            
+	            aggregator.addRawPacket(packet);
+	            
+	            // Should we try to get more packets?
+	            if( assembledPackets.isEmpty() ) {
+	                if( timeout == WAIT_FOREVER_TIMEOUT )
+	                    continue;
+	                
+	                timeout = Math.max(0, timeout-(System.currentTimeMillis()-start));
+	                if( timeout != 0 )
+	                    continue;
+	                
+	                return null;
+	            } else {
+	                return (Packet) assembledPackets.removeFirst();
+	            }
+            }
+            
+        } else {
+            return (Packet) assembledPackets.removeFirst();
+        }
+        
+    }
+    
+    public void write(Packet packet) throws IOException {
+        getNext().write(aggregator.getHeader(packet));
+        getNext().write(packet);
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PushbackSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PushbackSyncChannel.java
index ad8cc23..e236f62 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PushbackSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/PushbackSyncChannel.java
@@ -1,54 +1,54 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.filter;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.FilterSyncChannel;

-import org.apache.activeio.packet.sync.SyncChannel;

-

-/**

- *

- */

-public class PushbackSyncChannel extends FilterSyncChannel {

-

-    private Packet putback;

-

-    public PushbackSyncChannel(SyncChannel next) {

-        this(next, null);

-    }

-    

-    public PushbackSyncChannel(SyncChannel next, Packet putback) {

-        super(next);

-        this.putback=putback;

-    }

-    

-    public void putback(Packet packet) {

-        this.putback = packet;

-    }

-    

-    public Packet read(long timeout) throws IOException {

-        if(putback!=null ) {

-            Packet p = putback;

-            putback=null;

-            return p;

-        }

-        return super.read(timeout);

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.filter;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.FilterSyncChannel;
+import org.apache.activeio.packet.sync.SyncChannel;
+
+/**
+ *
+ */
+public class PushbackSyncChannel extends FilterSyncChannel {
+
+    private Packet putback;
+
+    public PushbackSyncChannel(SyncChannel next) {
+        this(next, null);
+    }
+    
+    public PushbackSyncChannel(SyncChannel next, Packet putback) {
+        super(next);
+        this.putback=putback;
+    }
+    
+    public void putback(Packet packet) {
+        this.putback = packet;
+    }
+    
+    public Packet read(long timeout) throws IOException {
+        if(putback!=null ) {
+            Packet p = putback;
+            putback=null;
+            return p;
+        }
+        return super.read(timeout);
+    }
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/SynchornizedSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/SynchornizedSyncChannel.java
index 2666b00..eb9cf99 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/SynchornizedSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/SynchornizedSyncChannel.java
@@ -1,118 +1,118 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.filter;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.FilterSyncChannel;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-import edu.emory.mathcs.backport.java.util.concurrent.locks.Lock;

-import edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock;

-

-/**

- * Used to synchronize concurrent access to a SynchChannel.  

- * 

- * Uses two different {@see edu.emory.mathcs.backport.java.util.concurrent.Sync} objects

- * for write and read operations.  All other operations such as {@see #stop(long)}

- * and {@see #stop} just do a normal java synchronization against the SynchornizedSynchChannel

- * object instance.

- * 

- */

-public class SynchornizedSyncChannel extends FilterSyncChannel {

-

-    private final Lock readLock;

-    private final Lock writeLock;

-

-    public SynchornizedSyncChannel(SyncChannel next) {

-        this(next, new ReentrantLock(), new ReentrantLock());

-    }

-    

-    public SynchornizedSyncChannel(SyncChannel next, Lock readLock, Lock writeLock) {

-        super(next);

-        this.readLock = readLock;

-        this.writeLock = writeLock;

-    }

-    

-    public Packet read(long timeout) throws IOException {

-        try {            

-            

-            if( timeout==SyncChannelServer.WAIT_FOREVER_TIMEOUT ) {

-                readLock.lock();

-            } else {

-                long start = System.currentTimeMillis();

-                if( !readLock.tryLock(0, TimeUnit.MILLISECONDS) ) {

-                    return null;

-                }

-                // Adjust the resulting timeout down to account for time taken to 

-                // get the readLock.

-                timeout = Math.max(0, timeout-(System.currentTimeMillis()-start));

-            }

-            

-        } catch (InterruptedException e) {

-            throw new InterruptedIOException(e.getMessage());            

-        }

-        

-        try {

-            return getNext().read(timeout);            

-        } finally {

-            readLock.unlock();

-        }

-    }

-    

-    public void write(Packet packet) throws IOException {

-        writeLock.lock();

-        try {

-            getNext().write(packet);            

-        } finally {

-            writeLock.unlock();

-        }

-    }

-    

-    public void flush() throws IOException {

-        writeLock.lock();

-        try {

-            getNext().flush();            

-        } finally {

-            writeLock.unlock();

-        }

-    }

-

-    synchronized public Object getAdapter(Class target) {

-        return super.getAdapter(target);

-    }

-

-    synchronized public void start() throws IOException {

-        super.start();

-    }

-

-    synchronized public void stop() throws IOException {

-        super.stop();

-    }

-    

-    public Lock getReadLock() {

-        return readLock;

-    }

-    

-    public Lock getWriteLock() {

-        return writeLock;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.filter;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.FilterSyncChannel;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+import edu.emory.mathcs.backport.java.util.concurrent.locks.Lock;
+import edu.emory.mathcs.backport.java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * Used to synchronize concurrent access to a SynchChannel.  
+ * 
+ * Uses two different {@see edu.emory.mathcs.backport.java.util.concurrent.Sync} objects
+ * for write and read operations.  All other operations such as {@see #stop(long)}
+ * and {@see #stop} just do a normal java synchronization against the SynchornizedSynchChannel
+ * object instance.
+ * 
+ */
+public class SynchornizedSyncChannel extends FilterSyncChannel {
+
+    private final Lock readLock;
+    private final Lock writeLock;
+
+    public SynchornizedSyncChannel(SyncChannel next) {
+        this(next, new ReentrantLock(), new ReentrantLock());
+    }
+    
+    public SynchornizedSyncChannel(SyncChannel next, Lock readLock, Lock writeLock) {
+        super(next);
+        this.readLock = readLock;
+        this.writeLock = writeLock;
+    }
+    
+    public Packet read(long timeout) throws IOException {
+        try {            
+            
+            if( timeout==SyncChannelServer.WAIT_FOREVER_TIMEOUT ) {
+                readLock.lock();
+            } else {
+                long start = System.currentTimeMillis();
+                if( !readLock.tryLock(0, TimeUnit.MILLISECONDS) ) {
+                    return null;
+                }
+                // Adjust the resulting timeout down to account for time taken to 
+                // get the readLock.
+                timeout = Math.max(0, timeout-(System.currentTimeMillis()-start));
+            }
+            
+        } catch (InterruptedException e) {
+            throw new InterruptedIOException(e.getMessage());            
+        }
+        
+        try {
+            return getNext().read(timeout);            
+        } finally {
+            readLock.unlock();
+        }
+    }
+    
+    public void write(Packet packet) throws IOException {
+        writeLock.lock();
+        try {
+            getNext().write(packet);            
+        } finally {
+            writeLock.unlock();
+        }
+    }
+    
+    public void flush() throws IOException {
+        writeLock.lock();
+        try {
+            getNext().flush();            
+        } finally {
+            writeLock.unlock();
+        }
+    }
+
+    synchronized public Object getAdapter(Class target) {
+        return super.getAdapter(target);
+    }
+
+    synchronized public void start() throws IOException {
+        super.start();
+    }
+
+    synchronized public void stop() throws IOException {
+        super.stop();
+    }
+    
+    public Lock getReadLock() {
+        return readLock;
+    }
+    
+    public Lock getWriteLock() {
+        return writeLock;
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/WriteBufferedSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/WriteBufferedSyncChannel.java
index 30f07e5..57fc760 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/WriteBufferedSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/filter/WriteBufferedSyncChannel.java
@@ -1,69 +1,69 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.filter;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.FilterSyncChannel;

-import org.apache.activeio.packet.sync.SyncChannel;

-

-/**

- */

-public class WriteBufferedSyncChannel extends FilterSyncChannel {

-

-    private static final int DEFAULT_BUFFER_SIZE = 1024*64;

-    private final Packet buffer;

-    private final boolean enableDirectWrites;

-    

-    public WriteBufferedSyncChannel(SyncChannel channel) {

-        this(channel, new ByteArrayPacket(new byte[DEFAULT_BUFFER_SIZE]));

-    }

-    

-    public WriteBufferedSyncChannel(SyncChannel channel, Packet buffer) {

-        this(channel, buffer, true);

-    }

-

-    public WriteBufferedSyncChannel(SyncChannel channel, Packet buffer, boolean enableDirectWrites) {

-        super(channel);

-        this.buffer = buffer;

-        this.enableDirectWrites = enableDirectWrites;

-    }

-

-    public void write(Packet packet) throws IOException {

-        

-        while( packet.hasRemaining() ) {

-	        packet.read(buffer);

-	        if( !buffer.hasRemaining() ) {

-	            flush();

-	            

-	            // Should we just direct write the rest?

-	            if( enableDirectWrites && packet.remaining() > buffer.capacity()) {

-	                getNext().write(packet);

-	                return;

-	            }

-	        }

-        }        

-    }

-    

-    public void flush() throws IOException {

-        buffer.flip();

-        getNext().write(buffer);

-        buffer.clear();

-    }    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.filter;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.FilterSyncChannel;
+import org.apache.activeio.packet.sync.SyncChannel;
+
+/**
+ */
+public class WriteBufferedSyncChannel extends FilterSyncChannel {
+
+    private static final int DEFAULT_BUFFER_SIZE = 1024*64;
+    private final Packet buffer;
+    private final boolean enableDirectWrites;
+    
+    public WriteBufferedSyncChannel(SyncChannel channel) {
+        this(channel, new ByteArrayPacket(new byte[DEFAULT_BUFFER_SIZE]));
+    }
+    
+    public WriteBufferedSyncChannel(SyncChannel channel, Packet buffer) {
+        this(channel, buffer, true);
+    }
+
+    public WriteBufferedSyncChannel(SyncChannel channel, Packet buffer, boolean enableDirectWrites) {
+        super(channel);
+        this.buffer = buffer;
+        this.enableDirectWrites = enableDirectWrites;
+    }
+
+    public void write(Packet packet) throws IOException {
+        
+        while( packet.hasRemaining() ) {
+	        packet.read(buffer);
+	        if( !buffer.hasRemaining() ) {
+	            flush();
+	            
+	            // Should we just direct write the rest?
+	            if( enableDirectWrites && packet.remaining() > buffer.capacity()) {
+	                getNext().write(packet);
+	                return;
+	            }
+	        }
+        }        
+    }
+    
+    public void flush() throws IOException {
+        buffer.flip();
+        getNext().write(buffer);
+        buffer.clear();
+    }    
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannel.java
index 7d735e4..0fdc3f2 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannel.java
@@ -1,50 +1,50 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.multicast;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.MulticastSocket;

-

-import org.apache.activeio.packet.sync.datagram.DatagramSocketSyncChannel;

-

-

-/**

- * @version $Revision$

- */

-final public class MulticastSocketSyncChannel extends DatagramSocketSyncChannel {

-

-    private final InetAddress groupAddress;

-

-

-    protected MulticastSocketSyncChannel(MulticastSocket socket, InetAddress groupAddress) throws IOException {

-        super(socket);

-        this.groupAddress = groupAddress;

-    }

-

-    public void start() throws IOException {

-        ((MulticastSocket) getSocket()).joinGroup(groupAddress);

-    }

-

-    public void stop() throws IOException {

-        ((MulticastSocket) getSocket()).leaveGroup(groupAddress);

-    }

-

-    public String toString() {

-        return "MulticastSocket Connection: " + getSocket().getLocalSocketAddress() + " -> " + getSocket().getRemoteSocketAddress();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.multicast;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.MulticastSocket;
+
+import org.apache.activeio.packet.sync.datagram.DatagramSocketSyncChannel;
+
+
+/**
+ * @version $Revision$
+ */
+final public class MulticastSocketSyncChannel extends DatagramSocketSyncChannel {
+
+    private final InetAddress groupAddress;
+
+
+    protected MulticastSocketSyncChannel(MulticastSocket socket, InetAddress groupAddress) throws IOException {
+        super(socket);
+        this.groupAddress = groupAddress;
+    }
+
+    public void start() throws IOException {
+        ((MulticastSocket) getSocket()).joinGroup(groupAddress);
+    }
+
+    public void stop() throws IOException {
+        ((MulticastSocket) getSocket()).leaveGroup(groupAddress);
+    }
+
+    public String toString() {
+        return "MulticastSocket Connection: " + getSocket().getLocalSocketAddress() + " -> " + getSocket().getRemoteSocketAddress();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannelFactory.java
index 103f740..5b2c9c9 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/multicast/MulticastSocketSyncChannelFactory.java
@@ -1,59 +1,59 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.multicast;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.MulticastSocket;

-import java.net.URI;

-

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-

-/**

- * @version $Revision: $ $Date: $

- */

-public class MulticastSocketSyncChannelFactory {

-

-    public SyncChannel openSyncChannel(URI groupURI) throws IOException {

-        if (groupURI == null) throw new IllegalArgumentException("group URI cannot be null");

-

-        MulticastSocket socket = new MulticastSocket(groupURI.getPort());

-

-        return createSyncChannel(socket, InetAddress.getByName(groupURI.getHost()));

-    }

-

-    public SyncChannel openSyncChannel(URI groupURI, URI localLocation) throws IOException {

-        if (groupURI == null) throw new IllegalArgumentException("group URI cannot be null");

-

-        MulticastSocket socket = new MulticastSocket(groupURI.getPort());

-        if (localLocation != null) {

-            socket.setInterface(InetAddress.getByName(localLocation.getHost()));

-        }

-

-        return createSyncChannel(socket, InetAddress.getByName(groupURI.getHost()));

-    }

-

-    protected SyncChannel createSyncChannel(MulticastSocket socket, InetAddress groupAddress) throws IOException {

-        return new MulticastSocketSyncChannel(socket, groupAddress);

-    }

-

-    public SyncChannelServer bindSyncChannel(URI location) throws IOException {

-        throw new IOException("A SyncChannelServer is not available for this channel.");

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.multicast;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.MulticastSocket;
+import java.net.URI;
+
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+
+/**
+ * @version $Revision: $ $Date: $
+ */
+public class MulticastSocketSyncChannelFactory {
+
+    public SyncChannel openSyncChannel(URI groupURI) throws IOException {
+        if (groupURI == null) throw new IllegalArgumentException("group URI cannot be null");
+
+        MulticastSocket socket = new MulticastSocket(groupURI.getPort());
+
+        return createSyncChannel(socket, InetAddress.getByName(groupURI.getHost()));
+    }
+
+    public SyncChannel openSyncChannel(URI groupURI, URI localLocation) throws IOException {
+        if (groupURI == null) throw new IllegalArgumentException("group URI cannot be null");
+
+        MulticastSocket socket = new MulticastSocket(groupURI.getPort());
+        if (localLocation != null) {
+            socket.setInterface(InetAddress.getByName(localLocation.getHost()));
+        }
+
+        return createSyncChannel(socket, InetAddress.getByName(groupURI.getHost()));
+    }
+
+    protected SyncChannel createSyncChannel(MulticastSocket socket, InetAddress groupAddress) throws IOException {
+        return new MulticastSocketSyncChannel(socket, groupAddress);
+    }
+
+    public SyncChannelServer bindSyncChannel(URI location) throws IOException {
+        throw new IOException("A SyncChannelServer is not available for this channel.");
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOBaseChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOBaseChannel.java
index 28000f0..be8d507 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOBaseChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOBaseChannel.java
@@ -1,181 +1,181 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.packet.sync.nio;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.Socket;

-import java.net.SocketAddress;

-import java.net.SocketException;

-import java.nio.ByteBuffer;

-import java.nio.channels.SocketChannel;

-

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.stream.sync.socket.SocketMetadata;

-

-/**

- * Base class for the Async and Sync implementations of NIO channels.

- * 

- * @version $Revision$

- */

-public class NIOBaseChannel implements SocketMetadata {

-

-	protected final SocketChannel socketChannel;

-    protected final Socket socket;

-	private final boolean useDirect;

-    private int curentSoTimeout;

-	private boolean disposed;

-    private final String name;

-

-    protected NIOBaseChannel(SocketChannel socketChannel, boolean useDirect) throws IOException {

-        this.socketChannel = socketChannel;

-		this.useDirect = useDirect;

-		this.socket = this.socketChannel.socket();

-

-        if( useDirect ) {

-            socket.setSendBufferSize(ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE);

-            socket.setReceiveBufferSize(ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE);

-        } else {

-            socket.setSendBufferSize(ByteBufferPacket.DEFAULT_BUFFER_SIZE);

-            socket.setReceiveBufferSize(ByteBufferPacket.DEFAULT_BUFFER_SIZE);

-        }		

-

-        this.name = "NIO Socket Connection: "+getLocalSocketAddress()+" -> "+getRemoteSocketAddress();

-    }

-    

-    protected ByteBuffer allocateBuffer() {

-        if( useDirect ) {

-            return ByteBuffer.allocateDirect(ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE);

-        } else {

-            return ByteBuffer.allocate(ByteBufferPacket.DEFAULT_BUFFER_SIZE);

-        }

-    }

-

-    public void setSoTimeout(int i) throws SocketException {

-        if( curentSoTimeout != i ) {

-            socket.setSoTimeout(i);

-            curentSoTimeout = i;

-        }

-    }

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-

-    public String toString() {

-        return name;

-    }

-

-	public void dispose() {

-        if (disposed)

-            return;

-

-        try {

-            socketChannel.close();

-        } catch (IOException ignore) {

-        }

-        disposed = true;

-	}

-

-    /**

-     * @see org.apache.activeio.Channel#flush()

-     */

-    public void flush() throws IOException {

-    }

-    

-    public InetAddress getInetAddress() {

-        return socket.getInetAddress();

-    }

-    public boolean getKeepAlive() throws SocketException {

-        return socket.getKeepAlive();

-    }

-    public InetAddress getLocalAddress() {

-        return socket.getLocalAddress();

-    }

-    public int getLocalPort() {

-        return socket.getLocalPort();

-    }

-    public SocketAddress getLocalSocketAddress() {

-        return socket.getLocalSocketAddress();

-    }

-    public boolean getOOBInline() throws SocketException {

-        return socket.getOOBInline();

-    }

-    public int getPort() {

-        return socket.getPort();

-    }

-    public int getReceiveBufferSize() throws SocketException {

-        return socket.getReceiveBufferSize();

-    }

-    public SocketAddress getRemoteSocketAddress() {

-        return socket.getRemoteSocketAddress();

-    }

-    public boolean getReuseAddress() throws SocketException {

-        return socket.getReuseAddress();

-    }

-    public int getSendBufferSize() throws SocketException {

-        return socket.getSendBufferSize();

-    }

-    public int getSoLinger() throws SocketException {

-        return socket.getSoLinger();

-    }

-    public int getSoTimeout() throws SocketException {

-        return socket.getSoTimeout();

-    }

-    public boolean getTcpNoDelay() throws SocketException {

-        return socket.getTcpNoDelay();

-    }

-    public int getTrafficClass() throws SocketException {

-        return socket.getTrafficClass();

-    }

-    public boolean isBound() {

-        return socket.isBound();

-    }

-    public boolean isClosed() {

-        return socket.isClosed();

-    }

-    public boolean isConnected() {

-        return socket.isConnected();

-    }

-    public void setKeepAlive(boolean on) throws SocketException {

-        socket.setKeepAlive(on);

-    }

-    public void setOOBInline(boolean on) throws SocketException {

-        socket.setOOBInline(on);

-    }

-    public void setReceiveBufferSize(int size) throws SocketException {

-        socket.setReceiveBufferSize(size);

-    }

-    public void setReuseAddress(boolean on) throws SocketException {

-        socket.setReuseAddress(on);

-    }

-    public void setSendBufferSize(int size) throws SocketException {

-        socket.setSendBufferSize(size);

-    }

-    public void setSoLinger(boolean on, int linger) throws SocketException {

-        socket.setSoLinger(on, linger);

-    }

-    public void setTcpNoDelay(boolean on) throws SocketException {

-        socket.setTcpNoDelay(on);

-    }

-    public void setTrafficClass(int tc) throws SocketException {

-        socket.setTrafficClass(tc);

-    }    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.packet.sync.nio;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.stream.sync.socket.SocketMetadata;
+
+/**
+ * Base class for the Async and Sync implementations of NIO channels.
+ * 
+ * @version $Revision$
+ */
+public class NIOBaseChannel implements SocketMetadata {
+
+	protected final SocketChannel socketChannel;
+    protected final Socket socket;
+	private final boolean useDirect;
+    private int curentSoTimeout;
+	private boolean disposed;
+    private final String name;
+
+    protected NIOBaseChannel(SocketChannel socketChannel, boolean useDirect) throws IOException {
+        this.socketChannel = socketChannel;
+		this.useDirect = useDirect;
+		this.socket = this.socketChannel.socket();
+
+        if( useDirect ) {
+            socket.setSendBufferSize(ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE);
+            socket.setReceiveBufferSize(ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE);
+        } else {
+            socket.setSendBufferSize(ByteBufferPacket.DEFAULT_BUFFER_SIZE);
+            socket.setReceiveBufferSize(ByteBufferPacket.DEFAULT_BUFFER_SIZE);
+        }		
+
+        this.name = "NIO Socket Connection: "+getLocalSocketAddress()+" -> "+getRemoteSocketAddress();
+    }
+    
+    protected ByteBuffer allocateBuffer() {
+        if( useDirect ) {
+            return ByteBuffer.allocateDirect(ByteBufferPacket.DEFAULT_DIRECT_BUFFER_SIZE);
+        } else {
+            return ByteBuffer.allocate(ByteBufferPacket.DEFAULT_BUFFER_SIZE);
+        }
+    }
+
+    public void setSoTimeout(int i) throws SocketException {
+        if( curentSoTimeout != i ) {
+            socket.setSoTimeout(i);
+            curentSoTimeout = i;
+        }
+    }
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+
+    public String toString() {
+        return name;
+    }
+
+	public void dispose() {
+        if (disposed)
+            return;
+
+        try {
+            socketChannel.close();
+        } catch (IOException ignore) {
+        }
+        disposed = true;
+	}
+
+    /**
+     * @see org.apache.activeio.Channel#flush()
+     */
+    public void flush() throws IOException {
+    }
+    
+    public InetAddress getInetAddress() {
+        return socket.getInetAddress();
+    }
+    public boolean getKeepAlive() throws SocketException {
+        return socket.getKeepAlive();
+    }
+    public InetAddress getLocalAddress() {
+        return socket.getLocalAddress();
+    }
+    public int getLocalPort() {
+        return socket.getLocalPort();
+    }
+    public SocketAddress getLocalSocketAddress() {
+        return socket.getLocalSocketAddress();
+    }
+    public boolean getOOBInline() throws SocketException {
+        return socket.getOOBInline();
+    }
+    public int getPort() {
+        return socket.getPort();
+    }
+    public int getReceiveBufferSize() throws SocketException {
+        return socket.getReceiveBufferSize();
+    }
+    public SocketAddress getRemoteSocketAddress() {
+        return socket.getRemoteSocketAddress();
+    }
+    public boolean getReuseAddress() throws SocketException {
+        return socket.getReuseAddress();
+    }
+    public int getSendBufferSize() throws SocketException {
+        return socket.getSendBufferSize();
+    }
+    public int getSoLinger() throws SocketException {
+        return socket.getSoLinger();
+    }
+    public int getSoTimeout() throws SocketException {
+        return socket.getSoTimeout();
+    }
+    public boolean getTcpNoDelay() throws SocketException {
+        return socket.getTcpNoDelay();
+    }
+    public int getTrafficClass() throws SocketException {
+        return socket.getTrafficClass();
+    }
+    public boolean isBound() {
+        return socket.isBound();
+    }
+    public boolean isClosed() {
+        return socket.isClosed();
+    }
+    public boolean isConnected() {
+        return socket.isConnected();
+    }
+    public void setKeepAlive(boolean on) throws SocketException {
+        socket.setKeepAlive(on);
+    }
+    public void setOOBInline(boolean on) throws SocketException {
+        socket.setOOBInline(on);
+    }
+    public void setReceiveBufferSize(int size) throws SocketException {
+        socket.setReceiveBufferSize(size);
+    }
+    public void setReuseAddress(boolean on) throws SocketException {
+        socket.setReuseAddress(on);
+    }
+    public void setSendBufferSize(int size) throws SocketException {
+        socket.setSendBufferSize(size);
+    }
+    public void setSoLinger(boolean on, int linger) throws SocketException {
+        socket.setSoLinger(on, linger);
+    }
+    public void setTcpNoDelay(boolean on) throws SocketException {
+        socket.setTcpNoDelay(on);
+    }
+    public void setTrafficClass(int tc) throws SocketException {
+        socket.setTrafficClass(tc);
+    }    
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannel.java
index f732980..7ef9c6a 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannel.java
@@ -1,104 +1,104 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.packet.sync.nio;

-

-import java.io.IOException;

-import java.net.SocketTimeoutException;

-import java.nio.ByteBuffer;

-import java.nio.channels.SocketChannel;

-

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.ByteSequence;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.EmptyPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-/**

- * A {@see org.apache.activeio.SynchChannel} implementation that uses a {@see java.nio.channels.SocketChannel}

- * to talk to the network.

- * 

- * Using a SocketChannelSynchChannel should be more efficient than using a SocketSynchChannel since

- * direct ByteBuffer can be used to reduce the jvm overhead needed to copy byte[]s.

- * 

- * @version $Revision$

- */

-final public class NIOSyncChannel extends NIOBaseChannel implements SyncChannel {

-

-    private ByteBuffer inputByteBuffer;

-//    private Packet data2;

-

-    protected NIOSyncChannel(SocketChannel socketChannel) throws IOException {

-        this(socketChannel, true );

-    }

-

-    protected NIOSyncChannel(SocketChannel socketChannel, boolean useDirect) throws IOException {

-        super(socketChannel, useDirect);

-    }

-    

-    public Packet read(long timeout) throws IOException {

-        try {

-            

-            if( timeout==SyncChannelServer.WAIT_FOREVER_TIMEOUT )

-                setSoTimeout( 0 );

-            else if( timeout==SyncChannelServer.NO_WAIT_TIMEOUT )

-                setSoTimeout( 1 );

-            else 

-                setSoTimeout( (int)timeout );

-

-            if( inputByteBuffer==null || !inputByteBuffer.hasRemaining() ) {

-                inputByteBuffer = allocateBuffer();

-            }

-

-            int size = socketChannel.read(inputByteBuffer);

-            if( size == -1 )

-                return EOSPacket.EOS_PACKET;

-            if( size == 0 )

-                return EmptyPacket.EMPTY_PACKET;

-

-            ByteBuffer remaining = inputByteBuffer.slice();            

-            Packet data = new ByteBufferPacket(((ByteBuffer)inputByteBuffer.flip()).slice());

-            

-            // Keep the remaining buffer around to fill with data.

-            inputByteBuffer = remaining;

-            return data;

-            

-        } catch (SocketTimeoutException e) {

-            return null;

-        }

-    }

-    

-    public void write(Packet packet) throws IOException {

-    	ByteBuffer data;

-        if( packet.getClass()==ByteBufferPacket.class ) {

-            data = ((ByteBufferPacket)packet).getByteBuffer();            

-        } else {

-        	ByteSequence sequence = packet.asByteSequence();

-        	data = ByteBuffer.wrap(sequence.getData(), sequence.getOffset(), sequence.getLength());

-        }

-        socketChannel.write( data );            

-    }

-

-	public void start() throws IOException {

-	}

-

-	public void stop() throws IOException {

-	}

-    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.packet.sync.nio;
+
+import java.io.IOException;
+import java.net.SocketTimeoutException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.ByteSequence;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.EmptyPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+/**
+ * A {@see org.apache.activeio.SynchChannel} implementation that uses a {@see java.nio.channels.SocketChannel}
+ * to talk to the network.
+ * 
+ * Using a SocketChannelSynchChannel should be more efficient than using a SocketSynchChannel since
+ * direct ByteBuffer can be used to reduce the jvm overhead needed to copy byte[]s.
+ * 
+ * @version $Revision$
+ */
+final public class NIOSyncChannel extends NIOBaseChannel implements SyncChannel {
+
+    private ByteBuffer inputByteBuffer;
+//    private Packet data2;
+
+    protected NIOSyncChannel(SocketChannel socketChannel) throws IOException {
+        this(socketChannel, true );
+    }
+
+    protected NIOSyncChannel(SocketChannel socketChannel, boolean useDirect) throws IOException {
+        super(socketChannel, useDirect);
+    }
+    
+    public Packet read(long timeout) throws IOException {
+        try {
+            
+            if( timeout==SyncChannelServer.WAIT_FOREVER_TIMEOUT )
+                setSoTimeout( 0 );
+            else if( timeout==SyncChannelServer.NO_WAIT_TIMEOUT )
+                setSoTimeout( 1 );
+            else 
+                setSoTimeout( (int)timeout );
+
+            if( inputByteBuffer==null || !inputByteBuffer.hasRemaining() ) {
+                inputByteBuffer = allocateBuffer();
+            }
+
+            int size = socketChannel.read(inputByteBuffer);
+            if( size == -1 )
+                return EOSPacket.EOS_PACKET;
+            if( size == 0 )
+                return EmptyPacket.EMPTY_PACKET;
+
+            ByteBuffer remaining = inputByteBuffer.slice();            
+            Packet data = new ByteBufferPacket(((ByteBuffer)inputByteBuffer.flip()).slice());
+            
+            // Keep the remaining buffer around to fill with data.
+            inputByteBuffer = remaining;
+            return data;
+            
+        } catch (SocketTimeoutException e) {
+            return null;
+        }
+    }
+    
+    public void write(Packet packet) throws IOException {
+    	ByteBuffer data;
+        if( packet.getClass()==ByteBufferPacket.class ) {
+            data = ((ByteBufferPacket)packet).getByteBuffer();            
+        } else {
+        	ByteSequence sequence = packet.asByteSequence();
+        	data = ByteBuffer.wrap(sequence.getData(), sequence.getOffset(), sequence.getLength());
+        }
+        socketChannel.write( data );            
+    }
+
+	public void start() throws IOException {
+	}
+
+	public void stop() throws IOException {
+	}
+    
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelFactory.java
index 47c3b73..9076eff 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelFactory.java
@@ -1,127 +1,127 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.nio;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.InetSocketAddress;

-import java.net.URI;

-import java.net.URISyntaxException;

-import java.nio.channels.ServerSocketChannel;

-import java.nio.channels.SocketChannel;

-

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.activeio.packet.sync.filter.WriteBufferedSyncChannel;

-import org.apache.activeio.util.URISupport;

-

-/**

- * A TcpSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}

- * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects.

- * 

- * @version $Revision$

- */

-public class NIOSyncChannelFactory implements SyncChannelFactory {

-

-    protected static final int DEFAULT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.net.nio.BufferSize", ""+(64*1024)));

-

-    protected static final int DEFAULT_BACKLOG = 500;

-    boolean useDirectBuffers = true;

-    private final boolean createWriteBufferedChannels;

-    private int backlog = DEFAULT_BACKLOG;

-    

-    public NIOSyncChannelFactory() {

-        this(true);

-    }

-    

-    public NIOSyncChannelFactory(boolean createWriteBufferedChannels) {

-        this.createWriteBufferedChannels = createWriteBufferedChannels;

-    }

-    

-    

-    /**

-     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.

-     * 

-     * @see org.apache.activeio.SynchChannelFactory#openSyncChannel(java.net.URI)

-     */

-    public SyncChannel openSyncChannel(URI location) throws IOException {

-        SocketChannel channel = SocketChannel.open();

-        channel.connect(new InetSocketAddress(location.getHost(), location.getPort()));

-        return createSynchChannel(channel);

-    }

-

-    /**

-     * @param channel

-     * @return

-     * @throws IOException

-     */

-    protected SyncChannel createSynchChannel(SocketChannel socketChannel) throws IOException {

-        SyncChannel channel = new NIOSyncChannel(socketChannel);

-        if( createWriteBufferedChannels ) {

-            channel = new WriteBufferedSyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers));

-        }

-        return channel;

-    }

-

-    /**

-     * Binds a server socket a the {@param location}'s port. 

-     * 

-     * @see org.apache.activeio.SynchChannelFactory#bindSynchChannel(java.net.URI)

-     */

-    public SyncChannelServer bindSyncChannel(URI bindURI) throws IOException {

-        

-        String host = bindURI.getHost();

-        InetSocketAddress address;

-        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            

-            address = new InetSocketAddress(bindURI.getPort());

-        } else {

-            address = new InetSocketAddress(bindURI.getHost(), bindURI.getPort());

-        }

-        

-        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

-        serverSocketChannel.socket().bind(address,backlog);

-        

-        URI connectURI = bindURI;

-        try {

-//            connectURI = URISupport.changeHost(connectURI, InetAddress.getLocalHost().getHostName());

-            connectURI = URISupport.changePort(connectURI, serverSocketChannel.socket().getLocalPort());

-        } catch (URISyntaxException e) {

-            throw (IOException)new IOException("Could not build connect URI: "+e).initCause(e);

-        }

-        

-        return new NIOSyncChannelServer(serverSocketChannel, bindURI, connectURI, createWriteBufferedChannels, useDirectBuffers);

-    }

-    

-    /**

-     * @return Returns the backlog.

-     */

-    public int getBacklog() {

-        return backlog;

-    }

-

-    /**

-     * @param backlog

-     *            The backlog to set.

-     */

-    public void setBacklog(int backlog) {

-        this.backlog = backlog;

-    }

-

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.nio;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.activeio.packet.sync.filter.WriteBufferedSyncChannel;
+import org.apache.activeio.util.URISupport;
+
+/**
+ * A TcpSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}
+ * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects.
+ * 
+ * @version $Revision$
+ */
+public class NIOSyncChannelFactory implements SyncChannelFactory {
+
+    protected static final int DEFAULT_BUFFER_SIZE = Integer.parseInt(System.getProperty("org.apache.activeio.net.nio.BufferSize", ""+(64*1024)));
+
+    protected static final int DEFAULT_BACKLOG = 500;
+    boolean useDirectBuffers = true;
+    private final boolean createWriteBufferedChannels;
+    private int backlog = DEFAULT_BACKLOG;
+    
+    public NIOSyncChannelFactory() {
+        this(true);
+    }
+    
+    public NIOSyncChannelFactory(boolean createWriteBufferedChannels) {
+        this.createWriteBufferedChannels = createWriteBufferedChannels;
+    }
+    
+    
+    /**
+     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
+     * 
+     * @see org.apache.activeio.SynchChannelFactory#openSyncChannel(java.net.URI)
+     */
+    public SyncChannel openSyncChannel(URI location) throws IOException {
+        SocketChannel channel = SocketChannel.open();
+        channel.connect(new InetSocketAddress(location.getHost(), location.getPort()));
+        return createSynchChannel(channel);
+    }
+
+    /**
+     * @param channel
+     * @return
+     * @throws IOException
+     */
+    protected SyncChannel createSynchChannel(SocketChannel socketChannel) throws IOException {
+        SyncChannel channel = new NIOSyncChannel(socketChannel);
+        if( createWriteBufferedChannels ) {
+            channel = new WriteBufferedSyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers));
+        }
+        return channel;
+    }
+
+    /**
+     * Binds a server socket a the {@param location}'s port. 
+     * 
+     * @see org.apache.activeio.SynchChannelFactory#bindSynchChannel(java.net.URI)
+     */
+    public SyncChannelServer bindSyncChannel(URI bindURI) throws IOException {
+        
+        String host = bindURI.getHost();
+        InetSocketAddress address;
+        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            
+            address = new InetSocketAddress(bindURI.getPort());
+        } else {
+            address = new InetSocketAddress(bindURI.getHost(), bindURI.getPort());
+        }
+        
+        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
+        serverSocketChannel.socket().bind(address,backlog);
+        
+        URI connectURI = bindURI;
+        try {
+//            connectURI = URISupport.changeHost(connectURI, InetAddress.getLocalHost().getHostName());
+            connectURI = URISupport.changePort(connectURI, serverSocketChannel.socket().getLocalPort());
+        } catch (URISyntaxException e) {
+            throw (IOException)new IOException("Could not build connect URI: "+e).initCause(e);
+        }
+        
+        return new NIOSyncChannelServer(serverSocketChannel, bindURI, connectURI, createWriteBufferedChannels, useDirectBuffers);
+    }
+    
+    /**
+     * @return Returns the backlog.
+     */
+    public int getBacklog() {
+        return backlog;
+    }
+
+    /**
+     * @param backlog
+     *            The backlog to set.
+     */
+    public void setBacklog(int backlog) {
+        this.backlog = backlog;
+    }
+
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelServer.java
index 5487836..46a496b 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/nio/NIOSyncChannelServer.java
@@ -1,56 +1,56 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.packet.sync.nio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.nio.channels.ServerSocketChannel;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.filter.WriteBufferedSyncChannel;

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelServer;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannel;

-

-/**

- * A SynchChannelServer that creates

- * {@see org.apache.activeio.net.TcpSynchChannel}objects from accepted

- * tcp socket connections.

- * 

- * @version $Revision$

- */

-public class NIOSyncChannelServer extends SocketSyncChannelServer {

-

-    private final boolean createWriteBufferedChannels;

-	private final boolean useDirectBuffers;

-

-    public NIOSyncChannelServer(ServerSocketChannel socketChannel, URI bindURI, URI connectURI, boolean createWriteBufferedChannels, boolean useDirectBuffers) {

-        super(socketChannel.socket(), bindURI, connectURI);

-        this.createWriteBufferedChannels = createWriteBufferedChannels;

-		this.useDirectBuffers = useDirectBuffers;

-    }

-    

-    protected Channel createChannel(SocketStreamChannel c) throws IOException {

-        SyncChannel channel = new NIOSyncChannel(c.getSocket().getChannel());

-        if( createWriteBufferedChannels ) {

-            channel = new WriteBufferedSyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers));

-        }

-        return channel;

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.packet.sync.nio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.channels.ServerSocketChannel;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.filter.WriteBufferedSyncChannel;
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelServer;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannel;
+
+/**
+ * A SynchChannelServer that creates
+ * {@see org.apache.activeio.net.TcpSynchChannel}objects from accepted
+ * tcp socket connections.
+ * 
+ * @version $Revision$
+ */
+public class NIOSyncChannelServer extends SocketSyncChannelServer {
+
+    private final boolean createWriteBufferedChannels;
+	private final boolean useDirectBuffers;
+
+    public NIOSyncChannelServer(ServerSocketChannel socketChannel, URI bindURI, URI connectURI, boolean createWriteBufferedChannels, boolean useDirectBuffers) {
+        super(socketChannel.socket(), bindURI, connectURI);
+        this.createWriteBufferedChannels = createWriteBufferedChannels;
+		this.useDirectBuffers = useDirectBuffers;
+    }
+    
+    protected Channel createChannel(SocketStreamChannel c) throws IOException {
+        SyncChannel channel = new NIOSyncChannel(c.getSocket().getChannel());
+        if( createWriteBufferedChannels ) {
+            channel = new WriteBufferedSyncChannel(channel, ByteBufferPacket.createDefaultBuffer(useDirectBuffers));
+        }
+        return channel;
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannel.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannel.java
index 1a45dc5..9459d99 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannel.java
@@ -1,144 +1,144 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.packet.sync.socket;

-

-import java.io.IOException;

-import java.io.InputStream;

-import java.io.OutputStream;

-import java.net.Socket;

-import java.net.SocketTimeoutException;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.ByteSequence;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.EmptyPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannel;

-

-/**

- * A {@see org.apache.activeio.SynchChannel} implementation that uses a {@see java.net.Socket}

- *  to talk to the network.

- * 

- * @version $Revision$

- */

-public class SocketSyncChannel implements SyncChannel {

-

-    protected static final int DEFAULT_BUFFER_SIZE = 64 * 1024;

-    private final SocketStreamChannel channel;

-    private Packet inputPacket;

-    private final OutputStream os;

-    private final InputStream is;

-    

-    protected SocketSyncChannel(Socket socket) throws IOException {

-        this(new SocketStreamChannel(socket));

-    }

-

-    public SocketSyncChannel(SocketStreamChannel channel) throws IOException {

-        this.channel = channel;

-        os = channel.getOutputStream();

-        is = channel.getInputStream();

-        channel.setReceiveBufferSize(DEFAULT_BUFFER_SIZE);

-        channel.setSendBufferSize(DEFAULT_BUFFER_SIZE);

-    }

-

-    /**

-     * @see org.apache.activeio.SynchChannel#read(long)

-     */

-    synchronized public org.apache.activeio.packet.Packet read(long timeout) throws IOException {

-        try {

-            

-            if( timeout==SyncChannelServer.WAIT_FOREVER_TIMEOUT )

-                channel.setSoTimeout( 0 );

-            else if( timeout==SyncChannelServer.NO_WAIT_TIMEOUT )

-                channel.setSoTimeout( 1 );

-            else 

-                channel.setSoTimeout( (int)timeout );

-

-            if( inputPacket==null || !inputPacket.hasRemaining() ) {

-                inputPacket = allocatePacket();

-            }

-            

-            ByteSequence sequence = inputPacket.asByteSequence();

-            int size = is.read(sequence.getData(), sequence.getOffset(), sequence.getLength());

-            if( size == -1 )

-                return EOSPacket.EOS_PACKET;

-            if( size == 0 )

-                return EmptyPacket.EMPTY_PACKET;

-            inputPacket.position(size);

-            

-            Packet remaining = inputPacket.slice();

-            

-            inputPacket.flip();

-            Packet data = inputPacket.slice();

-

-            // Keep the remaining buffer around to fill with data.

-            inputPacket = remaining;            

-            return data;

-            

-        } catch (SocketTimeoutException e) {

-            return null;

-        }

-    }

-

-    private Packet allocatePacket() {

-        byte[] data = new byte[DEFAULT_BUFFER_SIZE];

-        return new ByteArrayPacket(data);

-    }

-

-    

-    /**

-     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)

-     */

-    public void write(Packet packet) throws IOException {

-        packet.writeTo(os);

-    }

-

-    /**

-     * @see org.apache.activeio.Channel#flush()

-     */

-    public void flush() throws IOException {

-        os.flush();

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        channel.dispose();

-    }

-

-    public void start() throws IOException {

-        channel.start();

-    }

-    public void stop() throws IOException {

-        channel.stop();

-    }

-        

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return channel.getAdapter(target);

-    }

-

-    public String toString() {

-        return channel.toString();

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.packet.sync.socket;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.ByteSequence;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.EmptyPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannel;
+
+/**
+ * A {@see org.apache.activeio.SynchChannel} implementation that uses a {@see java.net.Socket}
+ *  to talk to the network.
+ * 
+ * @version $Revision$
+ */
+public class SocketSyncChannel implements SyncChannel {
+
+    protected static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
+    private final SocketStreamChannel channel;
+    private Packet inputPacket;
+    private final OutputStream os;
+    private final InputStream is;
+    
+    protected SocketSyncChannel(Socket socket) throws IOException {
+        this(new SocketStreamChannel(socket));
+    }
+
+    public SocketSyncChannel(SocketStreamChannel channel) throws IOException {
+        this.channel = channel;
+        os = channel.getOutputStream();
+        is = channel.getInputStream();
+        channel.setReceiveBufferSize(DEFAULT_BUFFER_SIZE);
+        channel.setSendBufferSize(DEFAULT_BUFFER_SIZE);
+    }
+
+    /**
+     * @see org.apache.activeio.SynchChannel#read(long)
+     */
+    synchronized public org.apache.activeio.packet.Packet read(long timeout) throws IOException {
+        try {
+            
+            if( timeout==SyncChannelServer.WAIT_FOREVER_TIMEOUT )
+                channel.setSoTimeout( 0 );
+            else if( timeout==SyncChannelServer.NO_WAIT_TIMEOUT )
+                channel.setSoTimeout( 1 );
+            else 
+                channel.setSoTimeout( (int)timeout );
+
+            if( inputPacket==null || !inputPacket.hasRemaining() ) {
+                inputPacket = allocatePacket();
+            }
+            
+            ByteSequence sequence = inputPacket.asByteSequence();
+            int size = is.read(sequence.getData(), sequence.getOffset(), sequence.getLength());
+            if( size == -1 )
+                return EOSPacket.EOS_PACKET;
+            if( size == 0 )
+                return EmptyPacket.EMPTY_PACKET;
+            inputPacket.position(size);
+            
+            Packet remaining = inputPacket.slice();
+            
+            inputPacket.flip();
+            Packet data = inputPacket.slice();
+
+            // Keep the remaining buffer around to fill with data.
+            inputPacket = remaining;            
+            return data;
+            
+        } catch (SocketTimeoutException e) {
+            return null;
+        }
+    }
+
+    private Packet allocatePacket() {
+        byte[] data = new byte[DEFAULT_BUFFER_SIZE];
+        return new ByteArrayPacket(data);
+    }
+
+    
+    /**
+     * @see org.apache.activeio.Channel#write(org.apache.activeio.packet.Packet)
+     */
+    public void write(Packet packet) throws IOException {
+        packet.writeTo(os);
+    }
+
+    /**
+     * @see org.apache.activeio.Channel#flush()
+     */
+    public void flush() throws IOException {
+        os.flush();
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        channel.dispose();
+    }
+
+    public void start() throws IOException {
+        channel.start();
+    }
+    public void stop() throws IOException {
+        channel.stop();
+    }
+        
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return channel.getAdapter(target);
+    }
+
+    public String toString() {
+        return channel.toString();
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelFactory.java
index 04d4de1..86b070d 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelFactory.java
@@ -1,96 +1,96 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.socket;

-

-import java.io.IOException;

-import java.net.URI;

-

-import javax.net.ServerSocketFactory;

-import javax.net.SocketFactory;

-

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.activeio.stream.sync.StreamChannelServer;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannel;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannelFactory;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannelServer;

-

-/**

- * A TcpSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}

- * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects.

- * 

- * @version $Revision$

- */

-public class SocketSyncChannelFactory implements SyncChannelFactory {

-

-    SocketStreamChannelFactory factory;

-    

-    public SocketSyncChannelFactory() {

-        this(SocketFactory.getDefault(), ServerSocketFactory.getDefault());

-    }

-

-    public SocketSyncChannelFactory(SocketFactory socketFactory, ServerSocketFactory serverSocketFactory) {

-        factory = new SocketStreamChannelFactory(socketFactory, serverSocketFactory);

-    }

-        

-    /**

-     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.

-     * 

-     * @see org.apache.activeio.SyncChannelFactory#openSyncChannel(java.net.URI)

-     */

-    public SyncChannel openSyncChannel(URI location) throws IOException {

-        SocketStreamChannel channel = (SocketStreamChannel) factory.openStreamChannel(location);

-        return createSynchChannel(channel);

-    }

-

-    /**

-     * @param channel

-     * @return

-     * @throws IOException

-     */

-    protected SyncChannel createSynchChannel(SocketStreamChannel channel) throws IOException {

-        return new SocketSyncChannel(channel);

-    }

-

-    /**

-     * Binds a server socket a the {@param bindURI}'s port.

-     * 

-     * @see org.apache.activeio.SyncChannelFactory#bindSyncChannel(java.net.URI)

-     */

-    public SyncChannelServer bindSyncChannel(URI bindURI) throws IOException {

-        StreamChannelServer server = factory.bindStreamChannel(bindURI);

-        return new SocketSyncChannelServer((SocketStreamChannelServer) server);

-    }

-    

-    /**

-     * @return Returns the backlog.

-     */

-    public int getBacklog() {

-        return factory.getBacklog();

-    }

-

-    /**

-     * @param backlog

-     *            The backlog to set.

-     */

-    public void setBacklog(int backlog) {

-        factory.setBacklog(backlog);

-    }

-

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.socket;
+
+import java.io.IOException;
+import java.net.URI;
+
+import javax.net.ServerSocketFactory;
+import javax.net.SocketFactory;
+
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.activeio.stream.sync.StreamChannelServer;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannel;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannelFactory;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannelServer;
+
+/**
+ * A TcpSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}
+ * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects.
+ * 
+ * @version $Revision$
+ */
+public class SocketSyncChannelFactory implements SyncChannelFactory {
+
+    SocketStreamChannelFactory factory;
+    
+    public SocketSyncChannelFactory() {
+        this(SocketFactory.getDefault(), ServerSocketFactory.getDefault());
+    }
+
+    public SocketSyncChannelFactory(SocketFactory socketFactory, ServerSocketFactory serverSocketFactory) {
+        factory = new SocketStreamChannelFactory(socketFactory, serverSocketFactory);
+    }
+        
+    /**
+     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
+     * 
+     * @see org.apache.activeio.SyncChannelFactory#openSyncChannel(java.net.URI)
+     */
+    public SyncChannel openSyncChannel(URI location) throws IOException {
+        SocketStreamChannel channel = (SocketStreamChannel) factory.openStreamChannel(location);
+        return createSynchChannel(channel);
+    }
+
+    /**
+     * @param channel
+     * @return
+     * @throws IOException
+     */
+    protected SyncChannel createSynchChannel(SocketStreamChannel channel) throws IOException {
+        return new SocketSyncChannel(channel);
+    }
+
+    /**
+     * Binds a server socket a the {@param bindURI}'s port.
+     * 
+     * @see org.apache.activeio.SyncChannelFactory#bindSyncChannel(java.net.URI)
+     */
+    public SyncChannelServer bindSyncChannel(URI bindURI) throws IOException {
+        StreamChannelServer server = factory.bindStreamChannel(bindURI);
+        return new SocketSyncChannelServer((SocketStreamChannelServer) server);
+    }
+    
+    /**
+     * @return Returns the backlog.
+     */
+    public int getBacklog() {
+        return factory.getBacklog();
+    }
+
+    /**
+     * @param backlog
+     *            The backlog to set.
+     */
+    public void setBacklog(int backlog) {
+        factory.setBacklog(backlog);
+    }
+
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelServer.java
index 55701c0..728724b 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelServer.java
@@ -1,99 +1,99 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.packet.sync.socket;

-

-import java.io.IOException;

-import java.net.ServerSocket;

-import java.net.URI;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannel;

-import org.apache.activeio.stream.sync.socket.SocketStreamChannelServer;

-

-/**

- * A SynchChannelServer that creates

- * {@see org.apache.activeio.net.TcpSynchChannel}objects from accepted

- * TCP socket connections.

- * 

- * @version $Revision$

- */

-public class SocketSyncChannelServer implements SyncChannelServer {

-

-    private final SocketStreamChannelServer server;

-

-    public SocketSyncChannelServer(SocketStreamChannelServer server) {

-        this.server = server;

-    }

-

-    public SocketSyncChannelServer(ServerSocket socket, URI bindURI, URI connectURI) {

-        this(new SocketStreamChannelServer(socket, bindURI, connectURI));

-    }

-

-    public Channel accept(long timeout) throws IOException {

-        Channel channel = server.accept(timeout);

-        if( channel != null ) {

-            channel = createChannel((SocketStreamChannel) channel);

-        }

-        return channel;

-    }

-

-    protected Channel createChannel(SocketStreamChannel channel) throws IOException {

-        return new SocketSyncChannel(channel);

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        server.dispose();

-    }

-

-    /**

-     * @return Returns the bindURI.

-     */

-    public URI getBindURI() {

-        return server.getBindURI();

-    }

-

-    /**

-     * @return Returns the connectURI.

-     */

-    public URI getConnectURI() {

-        return server.getConnectURI();

-    }

-

-    public void start() throws IOException {

-        server.start();

-    }

-

-    public void stop() throws IOException {

-        server.stop();

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return server.getAdapter(target);

-    }    

-    

-    public String toString() {

-        return server.toString();

-    }    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.packet.sync.socket;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.URI;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannel;
+import org.apache.activeio.stream.sync.socket.SocketStreamChannelServer;
+
+/**
+ * A SynchChannelServer that creates
+ * {@see org.apache.activeio.net.TcpSynchChannel}objects from accepted
+ * TCP socket connections.
+ * 
+ * @version $Revision$
+ */
+public class SocketSyncChannelServer implements SyncChannelServer {
+
+    private final SocketStreamChannelServer server;
+
+    public SocketSyncChannelServer(SocketStreamChannelServer server) {
+        this.server = server;
+    }
+
+    public SocketSyncChannelServer(ServerSocket socket, URI bindURI, URI connectURI) {
+        this(new SocketStreamChannelServer(socket, bindURI, connectURI));
+    }
+
+    public Channel accept(long timeout) throws IOException {
+        Channel channel = server.accept(timeout);
+        if( channel != null ) {
+            channel = createChannel((SocketStreamChannel) channel);
+        }
+        return channel;
+    }
+
+    protected Channel createChannel(SocketStreamChannel channel) throws IOException {
+        return new SocketSyncChannel(channel);
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        server.dispose();
+    }
+
+    /**
+     * @return Returns the bindURI.
+     */
+    public URI getBindURI() {
+        return server.getBindURI();
+    }
+
+    /**
+     * @return Returns the connectURI.
+     */
+    public URI getConnectURI() {
+        return server.getConnectURI();
+    }
+
+    public void start() throws IOException {
+        server.start();
+    }
+
+    public void stop() throws IOException {
+        server.stop();
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return server.getAdapter(target);
+    }    
+    
+    public String toString() {
+        return server.toString();
+    }    
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/packet/sync/ssl/SslSocketSyncChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/packet/sync/ssl/SslSocketSyncChannelFactory.java
index 799a6bb..b9e4c75 100644
--- a/activeio-core/src/main/java/org/apache/activeio/packet/sync/ssl/SslSocketSyncChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/packet/sync/ssl/SslSocketSyncChannelFactory.java
@@ -1,35 +1,35 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.ssl;

-

-import javax.net.ssl.SSLServerSocketFactory;

-import javax.net.ssl.SSLSocketFactory;

-

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;

-

-/**

- * A SslSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}

- * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects that use SSL.

- * 

- * @version $Revision$

- */

-public class SslSocketSyncChannelFactory extends SocketSyncChannelFactory {

-

-    public SslSocketSyncChannelFactory() {

-        super(SSLSocketFactory.getDefault(), SSLServerSocketFactory.getDefault());

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.ssl;
+
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSocketFactory;
+
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;
+
+/**
+ * A SslSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}
+ * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects that use SSL.
+ * 
+ * @version $Revision$
+ */
+public class SslSocketSyncChannelFactory extends SocketSyncChannelFactory {
+
+    public SslSocketSyncChannelFactory() {
+        super(SSLSocketFactory.getDefault(), SSLServerSocketFactory.getDefault());
+    }
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannel.java b/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannel.java
index 404fd7e..3732d7a 100644
--- a/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannel.java
@@ -1,33 +1,33 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.stream.sync;

-

-import java.io.IOException;

-import java.io.InputStream;

-import java.io.OutputStream;

-

-import org.apache.activeio.Channel;

-

-

-/**

- * @version $Revision$

- */

-public interface StreamChannel extends Channel {

-    InputStream getInputStream() throws IOException;

-    OutputStream getOutputStream() throws IOException;

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.stream.sync;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.activeio.Channel;
+
+
+/**
+ * @version $Revision$
+ */
+public interface StreamChannel extends Channel {
+    InputStream getInputStream() throws IOException;
+    OutputStream getOutputStream() throws IOException;
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelFactory.java
index 3bd24c4..19c5f23 100644
--- a/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelFactory.java
@@ -1,46 +1,46 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.stream.sync;

-

-import java.io.IOException;

-import java.net.URI;

-

-/**

- * StreamChannelFactory objects can create {@see org.apache.activeio.StreamChannel}

- * and {@see org.apache.activeio.StreamChannelServer} objects. 

- * 

- * @version $Revision$

- */

-public interface StreamChannelFactory {

-

-	/**

-     * Opens a connection to server.

-     * 

-     * @param location 

-     * @return

-     */

-	public StreamChannel openStreamChannel(URI location) throws IOException;

-	

-	/**

-     * Binds a server at the URI location.

-     * 

-     * @param location

-     * @return

-     */

-	public StreamChannelServer bindStreamChannel(URI location) throws IOException;

-	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.stream.sync;
+
+import java.io.IOException;
+import java.net.URI;
+
+/**
+ * StreamChannelFactory objects can create {@see org.apache.activeio.StreamChannel}
+ * and {@see org.apache.activeio.StreamChannelServer} objects. 
+ * 
+ * @version $Revision$
+ */
+public interface StreamChannelFactory {
+
+	/**
+     * Opens a connection to server.
+     * 
+     * @param location 
+     * @return
+     */
+	public StreamChannel openStreamChannel(URI location) throws IOException;
+	
+	/**
+     * Binds a server at the URI location.
+     * 
+     * @param location
+     * @return
+     */
+	public StreamChannelServer bindStreamChannel(URI location) throws IOException;
+	
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelServer.java
index 9c19502..7cc2187 100644
--- a/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/stream/sync/StreamChannelServer.java
@@ -1,39 +1,39 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.stream.sync;

-

-import java.io.IOException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-

-

-

-/**

- * A StreamChannelServer object provides an <code>accept</code> method to synchronously 

- * accept and create {@see org.apache.activeio.channel.Channel} objects.

- * 

- * @version $Revision$

- */

-public interface StreamChannelServer extends ChannelServer {

-

-    static final public long NO_WAIT_TIMEOUT=0;

-	static final public long WAIT_FOREVER_TIMEOUT=-1;	

-	

-	public Channel accept(long timeout) throws IOException;

-	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.stream.sync;
+
+import java.io.IOException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+
+
+
+/**
+ * A StreamChannelServer object provides an <code>accept</code> method to synchronously 
+ * accept and create {@see org.apache.activeio.channel.Channel} objects.
+ * 
+ * @version $Revision$
+ */
+public interface StreamChannelServer extends ChannelServer {
+
+    static final public long NO_WAIT_TIMEOUT=0;
+	static final public long WAIT_FOREVER_TIMEOUT=-1;	
+	
+	public Channel accept(long timeout) throws IOException;
+	
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketMetadata.java b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketMetadata.java
index 2eba046..260d42e 100644
--- a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketMetadata.java
+++ b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketMetadata.java
@@ -1,79 +1,79 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.stream.sync.socket;

-

-import java.net.InetAddress;

-import java.net.SocketAddress;

-import java.net.SocketException;

-

-/**

- */

-public interface SocketMetadata {

-    public InetAddress getInetAddress();

-

-    public boolean getKeepAlive() throws SocketException;

-

-    public InetAddress getLocalAddress();

-

-    public int getLocalPort();

-

-    public SocketAddress getLocalSocketAddress();

-

-    public int getPort();

-

-    public int getReceiveBufferSize() throws SocketException;

-

-    public SocketAddress getRemoteSocketAddress();

-

-    public boolean getReuseAddress() throws SocketException;

-

-    public int getSendBufferSize() throws SocketException;

-

-    public boolean getOOBInline() throws SocketException;

-

-    public int getSoLinger() throws SocketException;

-

-    public int getSoTimeout() throws SocketException;

-

-    public boolean getTcpNoDelay() throws SocketException;

-

-    public int getTrafficClass() throws SocketException;

-

-    public boolean isBound();

-

-    public boolean isClosed();

-

-    public boolean isConnected();

-

-    public void setKeepAlive(boolean on) throws SocketException;

-

-    public void setOOBInline(boolean on) throws SocketException;

-

-    public void setReceiveBufferSize(int size) throws SocketException;

-

-    public void setReuseAddress(boolean on) throws SocketException;

-

-    public void setSendBufferSize(int size) throws SocketException;

-

-    public void setSoLinger(boolean on, int linger) throws SocketException;

-    

-    public void setSoTimeout(int i) throws SocketException;

-

-    public void setTcpNoDelay(boolean on) throws SocketException;

-

-    public void setTrafficClass(int tc) throws SocketException;

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.stream.sync.socket;
+
+import java.net.InetAddress;
+import java.net.SocketAddress;
+import java.net.SocketException;
+
+/**
+ */
+public interface SocketMetadata {
+    public InetAddress getInetAddress();
+
+    public boolean getKeepAlive() throws SocketException;
+
+    public InetAddress getLocalAddress();
+
+    public int getLocalPort();
+
+    public SocketAddress getLocalSocketAddress();
+
+    public int getPort();
+
+    public int getReceiveBufferSize() throws SocketException;
+
+    public SocketAddress getRemoteSocketAddress();
+
+    public boolean getReuseAddress() throws SocketException;
+
+    public int getSendBufferSize() throws SocketException;
+
+    public boolean getOOBInline() throws SocketException;
+
+    public int getSoLinger() throws SocketException;
+
+    public int getSoTimeout() throws SocketException;
+
+    public boolean getTcpNoDelay() throws SocketException;
+
+    public int getTrafficClass() throws SocketException;
+
+    public boolean isBound();
+
+    public boolean isClosed();
+
+    public boolean isConnected();
+
+    public void setKeepAlive(boolean on) throws SocketException;
+
+    public void setOOBInline(boolean on) throws SocketException;
+
+    public void setReceiveBufferSize(int size) throws SocketException;
+
+    public void setReuseAddress(boolean on) throws SocketException;
+
+    public void setSendBufferSize(int size) throws SocketException;
+
+    public void setSoLinger(boolean on, int linger) throws SocketException;
+    
+    public void setSoTimeout(int i) throws SocketException;
+
+    public void setTcpNoDelay(boolean on) throws SocketException;
+
+    public void setTrafficClass(int tc) throws SocketException;
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannel.java b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannel.java
index d56a90a..5946a9e 100644
--- a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannel.java
+++ b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannel.java
@@ -1,186 +1,186 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.stream.sync.socket;

-

-import java.io.IOException;

-import java.io.InputStream;

-import java.io.OutputStream;

-import java.net.InetAddress;

-import java.net.Socket;

-import java.net.SocketAddress;

-import java.net.SocketException;

-

-import org.apache.activeio.stream.sync.StreamChannel;

-

-/**

- * A {@see org.apache.activeio.StreamChannel} implementation that uses a {@see java.net.Socket}

- *  to talk to the network.

- * 

- * @version $Revision$

- */

-public class SocketStreamChannel implements StreamChannel, SocketMetadata {

-

-    private final Socket socket;

-    private final OutputStream out;

-    private final InputStream in;    

-    private boolean disposed;

-    private int curentSoTimeout;

-

-    public SocketStreamChannel(Socket socket) throws IOException {

-        this.socket = socket;

-        in = socket.getInputStream();

-        out = socket.getOutputStream();        

-    }

-

-    public void setSoTimeout(int i) throws SocketException {

-        if( curentSoTimeout != i ) {

-            socket.setSoTimeout(i);

-            curentSoTimeout = i;

-        }

-    }

-    

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        if (disposed)

-            return;

-

-        try {

-            out.close();

-        } catch (IOException ignore) {

-        }

-        try {

-            in.close();

-        } catch (IOException ignore) {

-        }

-        try {

-            socket.close();

-        } catch (IOException ignore) {

-        }

-        disposed = true;

-    }

-

-    public void start() throws IOException {

-    }

-    public void stop() throws IOException {

-    }

-    

-    public InetAddress getInetAddress() {

-        return socket.getInetAddress();

-    }

-    public boolean getKeepAlive() throws SocketException {

-        return socket.getKeepAlive();

-    }

-    public InetAddress getLocalAddress() {

-        return socket.getLocalAddress();

-    }

-    public int getLocalPort() {

-        return socket.getLocalPort();

-    }

-    public SocketAddress getLocalSocketAddress() {

-        return socket.getLocalSocketAddress();

-    }

-    public boolean getOOBInline() throws SocketException {

-        return socket.getOOBInline();

-    }

-    public int getPort() {

-        return socket.getPort();

-    }

-    public int getReceiveBufferSize() throws SocketException {

-        return socket.getReceiveBufferSize();

-    }

-    public SocketAddress getRemoteSocketAddress() {

-        return socket.getRemoteSocketAddress();

-    }

-    public boolean getReuseAddress() throws SocketException {

-        return socket.getReuseAddress();

-    }

-    public int getSendBufferSize() throws SocketException {

-        return socket.getSendBufferSize();

-    }

-    public int getSoLinger() throws SocketException {

-        return socket.getSoLinger();

-    }

-    public int getSoTimeout() throws SocketException {

-        return socket.getSoTimeout();

-    }

-    public boolean getTcpNoDelay() throws SocketException {

-        return socket.getTcpNoDelay();

-    }

-    public int getTrafficClass() throws SocketException {

-        return socket.getTrafficClass();

-    }

-    public boolean isBound() {

-        return socket.isBound();

-    }

-    public boolean isClosed() {

-        return socket.isClosed();

-    }

-    public boolean isConnected() {

-        return socket.isConnected();

-    }

-    public void setKeepAlive(boolean on) throws SocketException {

-        socket.setKeepAlive(on);

-    }

-    public void setOOBInline(boolean on) throws SocketException {

-        socket.setOOBInline(on);

-    }

-    public void setReceiveBufferSize(int size) throws SocketException {

-        socket.setReceiveBufferSize(size);

-    }

-    public void setReuseAddress(boolean on) throws SocketException {

-        socket.setReuseAddress(on);

-    }

-    public void setSendBufferSize(int size) throws SocketException {

-        socket.setSendBufferSize(size);

-    }

-    public void setSoLinger(boolean on, int linger) throws SocketException {

-        socket.setSoLinger(on, linger);

-    }

-    public void setTcpNoDelay(boolean on) throws SocketException {

-        socket.setTcpNoDelay(on);

-    }

-    public void setTrafficClass(int tc) throws SocketException {

-        socket.setTrafficClass(tc);

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }

-

-    public String toString() {

-        return "Socket Connection: "+getLocalSocketAddress()+" -> "+getRemoteSocketAddress();

-    }

-

-    public InputStream getInputStream() throws IOException {

-        return in;

-    }

-

-    public OutputStream getOutputStream() throws IOException {

-        return out;

-    }

-

-    public Socket getSocket() {

-        return socket;

-    }

-

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.stream.sync.socket;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+
+import org.apache.activeio.stream.sync.StreamChannel;
+
+/**
+ * A {@see org.apache.activeio.StreamChannel} implementation that uses a {@see java.net.Socket}
+ *  to talk to the network.
+ * 
+ * @version $Revision$
+ */
+public class SocketStreamChannel implements StreamChannel, SocketMetadata {
+
+    private final Socket socket;
+    private final OutputStream out;
+    private final InputStream in;    
+    private boolean disposed;
+    private int curentSoTimeout;
+
+    public SocketStreamChannel(Socket socket) throws IOException {
+        this.socket = socket;
+        in = socket.getInputStream();
+        out = socket.getOutputStream();        
+    }
+
+    public void setSoTimeout(int i) throws SocketException {
+        if( curentSoTimeout != i ) {
+            socket.setSoTimeout(i);
+            curentSoTimeout = i;
+        }
+    }
+    
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        if (disposed)
+            return;
+
+        try {
+            out.close();
+        } catch (IOException ignore) {
+        }
+        try {
+            in.close();
+        } catch (IOException ignore) {
+        }
+        try {
+            socket.close();
+        } catch (IOException ignore) {
+        }
+        disposed = true;
+    }
+
+    public void start() throws IOException {
+    }
+    public void stop() throws IOException {
+    }
+    
+    public InetAddress getInetAddress() {
+        return socket.getInetAddress();
+    }
+    public boolean getKeepAlive() throws SocketException {
+        return socket.getKeepAlive();
+    }
+    public InetAddress getLocalAddress() {
+        return socket.getLocalAddress();
+    }
+    public int getLocalPort() {
+        return socket.getLocalPort();
+    }
+    public SocketAddress getLocalSocketAddress() {
+        return socket.getLocalSocketAddress();
+    }
+    public boolean getOOBInline() throws SocketException {
+        return socket.getOOBInline();
+    }
+    public int getPort() {
+        return socket.getPort();
+    }
+    public int getReceiveBufferSize() throws SocketException {
+        return socket.getReceiveBufferSize();
+    }
+    public SocketAddress getRemoteSocketAddress() {
+        return socket.getRemoteSocketAddress();
+    }
+    public boolean getReuseAddress() throws SocketException {
+        return socket.getReuseAddress();
+    }
+    public int getSendBufferSize() throws SocketException {
+        return socket.getSendBufferSize();
+    }
+    public int getSoLinger() throws SocketException {
+        return socket.getSoLinger();
+    }
+    public int getSoTimeout() throws SocketException {
+        return socket.getSoTimeout();
+    }
+    public boolean getTcpNoDelay() throws SocketException {
+        return socket.getTcpNoDelay();
+    }
+    public int getTrafficClass() throws SocketException {
+        return socket.getTrafficClass();
+    }
+    public boolean isBound() {
+        return socket.isBound();
+    }
+    public boolean isClosed() {
+        return socket.isClosed();
+    }
+    public boolean isConnected() {
+        return socket.isConnected();
+    }
+    public void setKeepAlive(boolean on) throws SocketException {
+        socket.setKeepAlive(on);
+    }
+    public void setOOBInline(boolean on) throws SocketException {
+        socket.setOOBInline(on);
+    }
+    public void setReceiveBufferSize(int size) throws SocketException {
+        socket.setReceiveBufferSize(size);
+    }
+    public void setReuseAddress(boolean on) throws SocketException {
+        socket.setReuseAddress(on);
+    }
+    public void setSendBufferSize(int size) throws SocketException {
+        socket.setSendBufferSize(size);
+    }
+    public void setSoLinger(boolean on, int linger) throws SocketException {
+        socket.setSoLinger(on, linger);
+    }
+    public void setTcpNoDelay(boolean on) throws SocketException {
+        socket.setTcpNoDelay(on);
+    }
+    public void setTrafficClass(int tc) throws SocketException {
+        socket.setTrafficClass(tc);
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }
+
+    public String toString() {
+        return "Socket Connection: "+getLocalSocketAddress()+" -> "+getRemoteSocketAddress();
+    }
+
+    public InputStream getInputStream() throws IOException {
+        return in;
+    }
+
+    public OutputStream getOutputStream() throws IOException {
+        return out;
+    }
+
+    public Socket getSocket() {
+        return socket;
+    }
+
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelFactory.java b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelFactory.java
index 569b58b..cc3fd4d 100644
--- a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelFactory.java
+++ b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelFactory.java
@@ -1,145 +1,145 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.stream.sync.socket;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.ServerSocket;

-import java.net.Socket;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import javax.net.ServerSocketFactory;

-import javax.net.SocketFactory;

-

-import org.apache.activeio.stream.sync.StreamChannel;

-import org.apache.activeio.stream.sync.StreamChannelFactory;

-import org.apache.activeio.stream.sync.StreamChannelServer;

-import org.apache.activeio.util.URISupport;

-

-/**

- * A TcpStreamChannelFactory creates {@see org.apache.activeio.net.TcpStreamChannel}

- * and {@see org.apache.activeio.net.TcpStreamChannelServer} objects.

- * 

- * @version $Revision$

- */

-public class SocketStreamChannelFactory implements StreamChannelFactory {

-

-    protected static final int DEFAULT_BACKLOG = 500;

-

-    private final SocketFactory socketFactory;

-    private final ServerSocketFactory serverSocketFactory;

-    private int backlog = DEFAULT_BACKLOG;

-    

-    public SocketStreamChannelFactory() {

-        this(SocketFactory.getDefault(), ServerSocketFactory.getDefault());

-    }

-

-    public SocketStreamChannelFactory(SocketFactory socketFactory, ServerSocketFactory serverSocketFactory) {

-        this.socketFactory = socketFactory;

-        this.serverSocketFactory = serverSocketFactory;

-    }

-        

-    /**

-     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.

-     * 

-     * @see org.apache.activeio.StreamChannelFactory#openStreamChannel(java.net.URI)

-     */

-    public StreamChannel openStreamChannel(URI location) throws IOException {

-        Socket socket=null;

-        String path=location.getPath();

-        // see if the path is a local URI location

-        if(path!=null&&path.length()>0){

-            if (path.indexOf('/')==0){

-                //strip leading slash

-                path = path.substring(1,path.length());

-            }

-            int localPortIndex=path.indexOf(':');

-            try{

-                int localPort = Integer.parseInt(path.substring((localPortIndex+1),path.length()));

-                InetAddress localAddress = InetAddress.getByName(path);

-                socket = socketFactory.createSocket(location.getHost(), location.getPort(),localAddress,localPort);

-            }catch(Exception e){

-                System.err.println("Could not define local address and port from path: " + path);

-                e.printStackTrace();

-            }

-        }

-        if (socket==null){

-            socket = socketFactory.createSocket(location.getHost(), location.getPort());

-        }

-        return createStreamChannel(socket);

-    }

-

-    /**

-     * @param socket

-     * @return

-     * @throws IOException

-     */

-    protected StreamChannel createStreamChannel(Socket socket) throws IOException {

-        return new SocketStreamChannel(socket);

-    }

-

-    /**

-     * Binds a server socket a the {@param bindURI}'s port.

-     * 

-     * @see org.apache.activeio.StreamChannelFactory#bindStreamChannel(java.net.URI)

-     */

-    public StreamChannelServer bindStreamChannel(URI bindURI) throws IOException {

-        

-        String host = bindURI.getHost();

-        InetAddress addr;

-        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            

-            addr = InetAddress.getLocalHost();

-        } else {

-            addr = InetAddress.getByName(host);

-        }

-        ServerSocket serverSocket;

-        

-        if (addr.equals(InetAddress.getLocalHost())) {

-            serverSocket = serverSocketFactory.createServerSocket(bindURI.getPort(), backlog);

-        } else {

-            serverSocket = serverSocketFactory.createServerSocket(bindURI.getPort(), backlog, addr);

-        }

-

-        URI connectURI=bindURI;

-        try {

-            // connectURI = URISupport.changeHost(connectURI, addr.getHostName());

-            connectURI = URISupport.changePort(connectURI, serverSocket.getLocalPort());

-        } catch (URISyntaxException e) {

-            throw (IOException)new IOException("Could build connect URI: "+e).initCause(e);

-        }

-        

-        return new SocketStreamChannelServer(serverSocket, bindURI, connectURI);

-    }

-    

-    /**

-     * @return Returns the backlog.

-     */

-    public int getBacklog() {

-        return backlog;

-    }

-

-    /**

-     * @param backlog

-     *            The backlog to set.

-     */

-    public void setBacklog(int backlog) {

-        this.backlog = backlog;

-    }

-

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.stream.sync.socket;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.net.ServerSocketFactory;
+import javax.net.SocketFactory;
+
+import org.apache.activeio.stream.sync.StreamChannel;
+import org.apache.activeio.stream.sync.StreamChannelFactory;
+import org.apache.activeio.stream.sync.StreamChannelServer;
+import org.apache.activeio.util.URISupport;
+
+/**
+ * A TcpStreamChannelFactory creates {@see org.apache.activeio.net.TcpStreamChannel}
+ * and {@see org.apache.activeio.net.TcpStreamChannelServer} objects.
+ * 
+ * @version $Revision$
+ */
+public class SocketStreamChannelFactory implements StreamChannelFactory {
+
+    protected static final int DEFAULT_BACKLOG = 500;
+
+    private final SocketFactory socketFactory;
+    private final ServerSocketFactory serverSocketFactory;
+    private int backlog = DEFAULT_BACKLOG;
+    
+    public SocketStreamChannelFactory() {
+        this(SocketFactory.getDefault(), ServerSocketFactory.getDefault());
+    }
+
+    public SocketStreamChannelFactory(SocketFactory socketFactory, ServerSocketFactory serverSocketFactory) {
+        this.socketFactory = socketFactory;
+        this.serverSocketFactory = serverSocketFactory;
+    }
+        
+    /**
+     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
+     * 
+     * @see org.apache.activeio.StreamChannelFactory#openStreamChannel(java.net.URI)
+     */
+    public StreamChannel openStreamChannel(URI location) throws IOException {
+        Socket socket=null;
+        String path=location.getPath();
+        // see if the path is a local URI location
+        if(path!=null&&path.length()>0){
+            if (path.indexOf('/')==0){
+                //strip leading slash
+                path = path.substring(1,path.length());
+            }
+            int localPortIndex=path.indexOf(':');
+            try{
+                int localPort = Integer.parseInt(path.substring((localPortIndex+1),path.length()));
+                InetAddress localAddress = InetAddress.getByName(path);
+                socket = socketFactory.createSocket(location.getHost(), location.getPort(),localAddress,localPort);
+            }catch(Exception e){
+                System.err.println("Could not define local address and port from path: " + path);
+                e.printStackTrace();
+            }
+        }
+        if (socket==null){
+            socket = socketFactory.createSocket(location.getHost(), location.getPort());
+        }
+        return createStreamChannel(socket);
+    }
+
+    /**
+     * @param socket
+     * @return
+     * @throws IOException
+     */
+    protected StreamChannel createStreamChannel(Socket socket) throws IOException {
+        return new SocketStreamChannel(socket);
+    }
+
+    /**
+     * Binds a server socket a the {@param bindURI}'s port.
+     * 
+     * @see org.apache.activeio.StreamChannelFactory#bindStreamChannel(java.net.URI)
+     */
+    public StreamChannelServer bindStreamChannel(URI bindURI) throws IOException {
+        
+        String host = bindURI.getHost();
+        InetAddress addr;
+        if( host == null || host.length() == 0 || host.equals("localhost") || host.equals("0.0.0.0") || InetAddress.getLocalHost().getHostName().equals(host) ) {            
+            addr = InetAddress.getLocalHost();
+        } else {
+            addr = InetAddress.getByName(host);
+        }
+        ServerSocket serverSocket;
+        
+        if (addr.equals(InetAddress.getLocalHost())) {
+            serverSocket = serverSocketFactory.createServerSocket(bindURI.getPort(), backlog);
+        } else {
+            serverSocket = serverSocketFactory.createServerSocket(bindURI.getPort(), backlog, addr);
+        }
+
+        URI connectURI=bindURI;
+        try {
+            // connectURI = URISupport.changeHost(connectURI, addr.getHostName());
+            connectURI = URISupport.changePort(connectURI, serverSocket.getLocalPort());
+        } catch (URISyntaxException e) {
+            throw (IOException)new IOException("Could build connect URI: "+e).initCause(e);
+        }
+        
+        return new SocketStreamChannelServer(serverSocket, bindURI, connectURI);
+    }
+    
+    /**
+     * @return Returns the backlog.
+     */
+    public int getBacklog() {
+        return backlog;
+    }
+
+    /**
+     * @param backlog
+     *            The backlog to set.
+     */
+    public void setBacklog(int backlog) {
+        this.backlog = backlog;
+    }
+
+
+}
diff --git a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelServer.java b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelServer.java
index e0833ee..b11a7fe 100644
--- a/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelServer.java
+++ b/activeio-core/src/main/java/org/apache/activeio/stream/sync/socket/SocketStreamChannelServer.java
@@ -1,127 +1,127 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-

-package org.apache.activeio.stream.sync.socket;

-

-import java.io.IOException;

-import java.net.ServerSocket;

-import java.net.Socket;

-import java.net.SocketException;

-import java.net.SocketTimeoutException;

-import java.net.URI;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.stream.sync.StreamChannelServer;

-

-/**

- * A StreamChannelServer that creates

- * {@see org.apache.activeio.net.TcpStreamChannel}objects from accepted

- * tcp socket connections.

- * 

- * @version $Revision$

- */

-public class SocketStreamChannelServer implements StreamChannelServer {

-

-    private ServerSocket serverSocket;

-    private int curentSoTimeout = 0;

-    private final URI bindURI;

-    private final URI connectURI;

-

-

-    /**

-     * @param serverSocket

-     * @param bindURI

-     * @param connectURI

-     */

-    public SocketStreamChannelServer(ServerSocket serverSocket, URI bindURI, URI connectURI) {

-        this.serverSocket=serverSocket;

-        this.bindURI=bindURI;

-        this.connectURI=connectURI;

-    }

-

-    public Channel accept(long timeout) throws IOException {

-        try {

-            if (timeout == StreamChannelServer.WAIT_FOREVER_TIMEOUT)

-                setSoTimeout(0);

-            else if (timeout == StreamChannelServer.NO_WAIT_TIMEOUT)

-                setSoTimeout(1);

-            else

-                setSoTimeout((int) timeout);

-

-            Socket socket = serverSocket.accept();

-            return createChannel(socket);

-

-        } catch (SocketTimeoutException ignore) {

-        }

-        return null;

-    }

-

-    protected Channel createChannel(Socket socket) throws IOException {

-        return new SocketStreamChannel(socket);

-    }

-

-    private void setSoTimeout(int i) throws SocketException {

-        if (curentSoTimeout != i) {

-            serverSocket.setSoTimeout(i);

-            curentSoTimeout = i;

-        }

-    }

-

-    /**

-     * @see org.apache.activeio.Disposable#dispose()

-     */

-    public void dispose() {

-        if (serverSocket == null)

-            return;

-        try {

-            serverSocket.close();

-        } catch (IOException ignore) {

-        }

-        serverSocket = null;

-    }

-

-    /**

-     * @return Returns the bindURI.

-     */

-    public URI getBindURI() {

-        return bindURI;

-    }

-

-    /**

-     * @return Returns the connectURI.

-     */

-    public URI getConnectURI() {

-        return connectURI;

-    }

-

-    public void start() throws IOException {

-    }

-

-    public void stop() throws IOException {

-    }

-    

-    public Object getAdapter(Class target) {

-        if( target.isAssignableFrom(getClass()) ) {

-            return this;

-        }

-        return null;

-    }    

-    

-    public String toString() {

-        return "Socket Server: "+getConnectURI();

-    }    

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+
+package org.apache.activeio.stream.sync.socket;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.stream.sync.StreamChannelServer;
+
+/**
+ * A StreamChannelServer that creates
+ * {@see org.apache.activeio.net.TcpStreamChannel}objects from accepted
+ * tcp socket connections.
+ * 
+ * @version $Revision$
+ */
+public class SocketStreamChannelServer implements StreamChannelServer {
+
+    private ServerSocket serverSocket;
+    private int curentSoTimeout = 0;
+    private final URI bindURI;
+    private final URI connectURI;
+
+
+    /**
+     * @param serverSocket
+     * @param bindURI
+     * @param connectURI
+     */
+    public SocketStreamChannelServer(ServerSocket serverSocket, URI bindURI, URI connectURI) {
+        this.serverSocket=serverSocket;
+        this.bindURI=bindURI;
+        this.connectURI=connectURI;
+    }
+
+    public Channel accept(long timeout) throws IOException {
+        try {
+            if (timeout == StreamChannelServer.WAIT_FOREVER_TIMEOUT)
+                setSoTimeout(0);
+            else if (timeout == StreamChannelServer.NO_WAIT_TIMEOUT)
+                setSoTimeout(1);
+            else
+                setSoTimeout((int) timeout);
+
+            Socket socket = serverSocket.accept();
+            return createChannel(socket);
+
+        } catch (SocketTimeoutException ignore) {
+        }
+        return null;
+    }
+
+    protected Channel createChannel(Socket socket) throws IOException {
+        return new SocketStreamChannel(socket);
+    }
+
+    private void setSoTimeout(int i) throws SocketException {
+        if (curentSoTimeout != i) {
+            serverSocket.setSoTimeout(i);
+            curentSoTimeout = i;
+        }
+    }
+
+    /**
+     * @see org.apache.activeio.Disposable#dispose()
+     */
+    public void dispose() {
+        if (serverSocket == null)
+            return;
+        try {
+            serverSocket.close();
+        } catch (IOException ignore) {
+        }
+        serverSocket = null;
+    }
+
+    /**
+     * @return Returns the bindURI.
+     */
+    public URI getBindURI() {
+        return bindURI;
+    }
+
+    /**
+     * @return Returns the connectURI.
+     */
+    public URI getConnectURI() {
+        return connectURI;
+    }
+
+    public void start() throws IOException {
+    }
+
+    public void stop() throws IOException {
+    }
+    
+    public Object getAdapter(Class target) {
+        if( target.isAssignableFrom(getClass()) ) {
+            return this;
+        }
+        return null;
+    }    
+    
+    public String toString() {
+        return "Socket Server: "+getConnectURI();
+    }    
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/util/FactoryFinder.java b/activeio-core/src/main/java/org/apache/activeio/util/FactoryFinder.java
index b9e06d0..f8d3178 100644
--- a/activeio-core/src/main/java/org/apache/activeio/util/FactoryFinder.java
+++ b/activeio-core/src/main/java/org/apache/activeio/util/FactoryFinder.java
@@ -1,105 +1,105 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.util;

-

-import java.io.BufferedInputStream;

-import java.io.IOException;

-import java.io.InputStream;

-import java.util.Properties;

-

-import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;

-

-

-public class FactoryFinder {

-

-    private final String path;

-    private final ConcurrentHashMap classMap = new ConcurrentHashMap();

-

-    public FactoryFinder(String path) {

-        this.path = path;

-    }

-

-    /**

-     * Creates a new instance of the given key

-     *

-     * @param key is the key to add to the path to find a text file

-     *            containing the factory name

-     * @return a newly created instance

-     */

-    public Object newInstance(String key)

-            throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException

-    {

-        return newInstance(key, null);

-    }

-

-    public Object newInstance(String key, String propertyPrefix)

-            throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException

-    {

-        if (propertyPrefix == null)

-            propertyPrefix = "";

-

-        Class clazz = (Class) classMap.get(propertyPrefix + key);

-        if (clazz == null) {

-            clazz = newInstance(doFindFactoryProperies(key), propertyPrefix);

-            classMap.put(propertyPrefix + key, clazz);

-        }

-        return clazz.newInstance();

-    }

-

-    private Class newInstance(Properties properties, String propertyPrefix) throws ClassNotFoundException, IOException {

-

-        String className = properties.getProperty(propertyPrefix + "class");

-        if (className == null) {

-            throw new IOException("Expected property is missing: " + propertyPrefix + "class");

-        }

-        Class clazz;

-        try {

-            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);

-        } catch (ClassNotFoundException e) {

-            clazz = FactoryFinder.class.getClassLoader().loadClass(className);

-        }

-

-        return clazz;

-    }

-

-    private Properties doFindFactoryProperies(String key) throws IOException {

-        String uri = path + key;

-

-        // lets try the thread context class loader first

-        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(uri);

-        if (in == null) {

-            in = FactoryFinder.class.getClassLoader().getResourceAsStream(uri);

-            if (in == null) {

-                throw new IOException("Could not find factory class for resource: " + uri);

-            }

-        }

-

-        // lets load the file

-        BufferedInputStream reader = null;

-        try {

-            reader = new BufferedInputStream(in);

-            Properties properties = new Properties();

-            properties.load(reader);

-            return properties;

-        } finally {

-            try {

-                reader.close();

-            } catch (Exception e) {

-            }

-        }

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.util;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
+
+
+public class FactoryFinder {
+
+    private final String path;
+    private final ConcurrentHashMap classMap = new ConcurrentHashMap();
+
+    public FactoryFinder(String path) {
+        this.path = path;
+    }
+
+    /**
+     * Creates a new instance of the given key
+     *
+     * @param key is the key to add to the path to find a text file
+     *            containing the factory name
+     * @return a newly created instance
+     */
+    public Object newInstance(String key)
+            throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException
+    {
+        return newInstance(key, null);
+    }
+
+    public Object newInstance(String key, String propertyPrefix)
+            throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException
+    {
+        if (propertyPrefix == null)
+            propertyPrefix = "";
+
+        Class clazz = (Class) classMap.get(propertyPrefix + key);
+        if (clazz == null) {
+            clazz = newInstance(doFindFactoryProperies(key), propertyPrefix);
+            classMap.put(propertyPrefix + key, clazz);
+        }
+        return clazz.newInstance();
+    }
+
+    private Class newInstance(Properties properties, String propertyPrefix) throws ClassNotFoundException, IOException {
+
+        String className = properties.getProperty(propertyPrefix + "class");
+        if (className == null) {
+            throw new IOException("Expected property is missing: " + propertyPrefix + "class");
+        }
+        Class clazz;
+        try {
+            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
+        } catch (ClassNotFoundException e) {
+            clazz = FactoryFinder.class.getClassLoader().loadClass(className);
+        }
+
+        return clazz;
+    }
+
+    private Properties doFindFactoryProperies(String key) throws IOException {
+        String uri = path + key;
+
+        // lets try the thread context class loader first
+        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(uri);
+        if (in == null) {
+            in = FactoryFinder.class.getClassLoader().getResourceAsStream(uri);
+            if (in == null) {
+                throw new IOException("Could not find factory class for resource: " + uri);
+            }
+        }
+
+        // lets load the file
+        BufferedInputStream reader = null;
+        try {
+            reader = new BufferedInputStream(in);
+            Properties properties = new Properties();
+            properties.load(reader);
+            return properties;
+        } finally {
+            try {
+                reader.close();
+            } catch (Exception e) {
+            }
+        }
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/util/PacketAggregator.java b/activeio-core/src/main/java/org/apache/activeio/util/PacketAggregator.java
index baa1d87..9f6f06b 100644
--- a/activeio-core/src/main/java/org/apache/activeio/util/PacketAggregator.java
+++ b/activeio-core/src/main/java/org/apache/activeio/util/PacketAggregator.java
@@ -1,101 +1,101 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.util;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.AppendedPacket;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.PacketData;

-

-/**

- * @version $Revision$

- */

-abstract public class PacketAggregator {

-

-    private static final int HEADER_LENGTH = 4;        

-    

-    private final ByteArrayPacket headerBuffer = new ByteArrayPacket(new byte[HEADER_LENGTH]);

-    private final PacketData headerData = new PacketData(headerBuffer);

-

-    Packet incompleteUpPacket;

-    boolean headerLoaded;

-    private int upPacketLength;

-    

-    public void addRawPacket(Packet packet) throws IOException {

-

-        // Passthrough the EOS packet.

-        if( packet == EOSPacket.EOS_PACKET ) {

-            packetAssembled(packet);

-            return;

-        }

-

-        if (incompleteUpPacket != null) {

-            packet = AppendedPacket.join(incompleteUpPacket, packet);

-            incompleteUpPacket = null;

-        }

-

-        while (true) {

-

-            if (!headerLoaded) {

-                headerLoaded = packet.remaining() >= HEADER_LENGTH;

-                if( headerLoaded ) {

-                    PacketData data = new PacketData(packet);

-                    upPacketLength = data.readInt();

-                    if( upPacketLength < 0 ) {

-                        throw new IOException("Up packet lenth was invalid: "+upPacketLength);

-                    }

-                    packet = packet.slice();

-                }

-                if( !headerLoaded )

-                    break;

-            }

-

-            if (packet.remaining() < upPacketLength )

-                break;

-

-            // Get ready to create a slice to send up.

-            int origLimit = packet.limit();

-            packet.limit(upPacketLength);

-            packetAssembled(packet.slice());

-            

-            // Get a slice of the remaining since that will dump

-            // the first packets of an AppendedPacket

-            packet.position(upPacketLength);

-            packet.limit(origLimit);

-            packet = packet.slice();

-

-            // Need to load a header again now.

-            headerLoaded = false;

-        }

-        if (packet.hasRemaining()) {

-            incompleteUpPacket = packet;

-        }

-        

-    }

-

-    protected abstract void packetAssembled(Packet packet);

-    

-    public Packet getHeader( Packet packet ) throws IOException {

-        headerBuffer.clear();

-        headerData.writeInt(packet.remaining());

-        headerBuffer.flip();

-        return headerBuffer;

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.util;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.AppendedPacket;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.PacketData;
+
+/**
+ * @version $Revision$
+ */
+abstract public class PacketAggregator {
+
+    private static final int HEADER_LENGTH = 4;        
+    
+    private final ByteArrayPacket headerBuffer = new ByteArrayPacket(new byte[HEADER_LENGTH]);
+    private final PacketData headerData = new PacketData(headerBuffer);
+
+    Packet incompleteUpPacket;
+    boolean headerLoaded;
+    private int upPacketLength;
+    
+    public void addRawPacket(Packet packet) throws IOException {
+
+        // Passthrough the EOS packet.
+        if( packet == EOSPacket.EOS_PACKET ) {
+            packetAssembled(packet);
+            return;
+        }
+
+        if (incompleteUpPacket != null) {
+            packet = AppendedPacket.join(incompleteUpPacket, packet);
+            incompleteUpPacket = null;
+        }
+
+        while (true) {
+
+            if (!headerLoaded) {
+                headerLoaded = packet.remaining() >= HEADER_LENGTH;
+                if( headerLoaded ) {
+                    PacketData data = new PacketData(packet);
+                    upPacketLength = data.readInt();
+                    if( upPacketLength < 0 ) {
+                        throw new IOException("Up packet lenth was invalid: "+upPacketLength);
+                    }
+                    packet = packet.slice();
+                }
+                if( !headerLoaded )
+                    break;
+            }
+
+            if (packet.remaining() < upPacketLength )
+                break;
+
+            // Get ready to create a slice to send up.
+            int origLimit = packet.limit();
+            packet.limit(upPacketLength);
+            packetAssembled(packet.slice());
+            
+            // Get a slice of the remaining since that will dump
+            // the first packets of an AppendedPacket
+            packet.position(upPacketLength);
+            packet.limit(origLimit);
+            packet = packet.slice();
+
+            // Need to load a header again now.
+            headerLoaded = false;
+        }
+        if (packet.hasRemaining()) {
+            incompleteUpPacket = packet;
+        }
+        
+    }
+
+    protected abstract void packetAssembled(Packet packet);
+    
+    public Packet getHeader( Packet packet ) throws IOException {
+        headerBuffer.clear();
+        headerData.writeInt(packet.remaining());
+        headerBuffer.flip();
+        return headerBuffer;
+    }
 }
\ No newline at end of file
diff --git a/activeio-core/src/main/java/org/apache/activeio/util/URISupport.java b/activeio-core/src/main/java/org/apache/activeio/util/URISupport.java
index 7ce009e..f6ba99f 100644
--- a/activeio-core/src/main/java/org/apache/activeio/util/URISupport.java
+++ b/activeio-core/src/main/java/org/apache/activeio/util/URISupport.java
@@ -1,52 +1,52 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.util;

-

-import java.net.URI;

-import java.net.URISyntaxException;

-

-/**

- * The URISupport class provides a few static methods that provides a few usefull

- * operations to manipulate URIs.

- * 

- * @version $Revision$

- */

-public class URISupport {

-    

-    static public URI changePort(URI bindAddr, int port) throws URISyntaxException {

-        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), port, bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());

-    }

-    static public URI changeScheme(URI bindAddr, String scheme) throws URISyntaxException {

-        return new URI(scheme, bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());

-    }

-    static public URI changeUserInfo(URI bindAddr, String userInfo) throws URISyntaxException {

-        return new URI(bindAddr.getScheme(), userInfo, bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());

-    }

-    static public URI changeHost(URI bindAddr, String host) throws URISyntaxException {

-        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), host, bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());

-    }

-    static public URI changePath(URI bindAddr, String path) throws URISyntaxException {

-        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), path, bindAddr.getQuery(), bindAddr.getFragment());

-    }

-    static public URI changeQuery(URI bindAddr, String query) throws URISyntaxException {

-        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), query, bindAddr.getFragment());

-    }

-    static public URI changeFragment(URI bindAddr, String fragment) throws URISyntaxException {

-        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), fragment);

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.util;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+/**
+ * The URISupport class provides a few static methods that provides a few usefull
+ * operations to manipulate URIs.
+ * 
+ * @version $Revision$
+ */
+public class URISupport {
+    
+    static public URI changePort(URI bindAddr, int port) throws URISyntaxException {
+        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), port, bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());
+    }
+    static public URI changeScheme(URI bindAddr, String scheme) throws URISyntaxException {
+        return new URI(scheme, bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());
+    }
+    static public URI changeUserInfo(URI bindAddr, String userInfo) throws URISyntaxException {
+        return new URI(bindAddr.getScheme(), userInfo, bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());
+    }
+    static public URI changeHost(URI bindAddr, String host) throws URISyntaxException {
+        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), host, bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());
+    }
+    static public URI changePath(URI bindAddr, String path) throws URISyntaxException {
+        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), path, bindAddr.getQuery(), bindAddr.getFragment());
+    }
+    static public URI changeQuery(URI bindAddr, String query) throws URISyntaxException {
+        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), query, bindAddr.getFragment());
+    }
+    static public URI changeFragment(URI bindAddr, String fragment) throws URISyntaxException {
+        return new URI(bindAddr.getScheme(), bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), fragment);
+    }
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/ChannelFactoryTest.java b/activeio-core/src/test/java/org/apache/activeio/ChannelFactoryTest.java
index b702633..35aee02 100644
--- a/activeio-core/src/test/java/org/apache/activeio/ChannelFactoryTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/ChannelFactoryTest.java
@@ -1,141 +1,141 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import junit.framework.TestCase;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelFactory;

-import org.apache.activeio.adapter.AsyncToSyncChannel;

-import org.apache.activeio.adapter.SyncToAsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.async.nio.NIOAsyncChannel;

-import org.apache.activeio.packet.async.nio.NIOAsyncChannelServer;

-import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelPipe;

-import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.activeio.packet.sync.nio.NIOSyncChannel;

-import org.apache.activeio.packet.sync.nio.NIOSyncChannelServer;

-import org.apache.activeio.packet.sync.socket.SocketSyncChannel;

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelServer;

-import org.apache.commons.logging.Log;

-import org.apache.commons.logging.LogFactory;

-

-import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- */

-public class ChannelFactoryTest extends TestCase {

-

-    static final Log log = LogFactory.getLog(ChannelFactoryTest.class);

-    static boolean aioDisabled = System.getProperty("disable.aio.tests", "false").equals("true");

-

-    ChannelFactory factory = new ChannelFactory();

-

-    private SyncChannelServer syncChannelServer;

-    private SyncChannel clientSynchChannel;

-    private SyncChannel serverSynchChannel;

-

-    private AsyncChannelServer asyncChannelServer;

-    private AsyncChannel clientAsyncChannel;

-    private AsyncChannel serverAsyncChannel;

-    

-    protected void setUp() throws Exception {

-        log.info("Running: "+getName());

-    }

-

-    public void testSocket() throws IOException, URISyntaxException, InterruptedException {

-        

-        createSynchObjects("socket://localhost:0");

-        assertNotNull( syncChannelServer.getAdapter(SocketSyncChannelServer.class) );

-        assertNotNull( clientSynchChannel.getAdapter(SocketSyncChannel.class) );

-        assertNotNull( serverSynchChannel.getAdapter(SocketSyncChannel.class) );

-        

-        createAsynchObjects("socket://localhost:0");

-        assertNotNull( asyncChannelServer.getAdapter(SocketSyncChannelServer.class) );

-        assertNotNull( clientAsyncChannel.getAdapter(SocketSyncChannel.class) );

-        assertNotNull( serverAsyncChannel.getAdapter(SocketSyncChannel.class) );

-        

-    }

-

-    public void testNIO() throws IOException, URISyntaxException, InterruptedException {

-        

-        createSynchObjects("nio://localhost:0");

-        assertNotNull( syncChannelServer.getAdapter(NIOSyncChannelServer.class) );

-        assertNotNull( clientSynchChannel.getAdapter(NIOSyncChannel.class) );

-        assertNotNull( serverSynchChannel.getAdapter(NIOSyncChannel.class) );

-        

-        createAsynchObjects("nio://localhost:0");

-        assertNotNull( asyncChannelServer.getAdapter(NIOAsyncChannelServer.class) );

-        assertNotNull( clientAsyncChannel.getAdapter(NIOAsyncChannel.class) );

-        assertNotNull( serverAsyncChannel.getAdapter(NIOAsyncChannel.class) );

-        

-    }    

-

-    public void testVMPipe() throws IOException, URISyntaxException, InterruptedException {

-        

-        createSynchObjects("vmpipe://localhost");

-        assertNotNull( syncChannelServer.getAdapter(VMPipeAsyncChannelServer.class) );

-        assertNotNull( clientSynchChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );

-        assertNotNull( serverSynchChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );

-        

-        createAsynchObjects("vmpipe://localhost");

-        assertNotNull( asyncChannelServer.getAdapter(VMPipeAsyncChannelServer.class) );

-        assertNotNull( clientAsyncChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );

-        assertNotNull( serverAsyncChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );

-        

-    }    

-    

-    private void createSynchObjects(String bindURI) throws IOException, URISyntaxException {

-        syncChannelServer = factory.bindSyncChannel(new URI(bindURI));

-        syncChannelServer.start();

-        clientSynchChannel = factory.openSyncChannel(syncChannelServer.getConnectURI());

-        serverSynchChannel = AsyncToSyncChannel.adapt( syncChannelServer.accept(1000*5) );

-        serverSynchChannel.dispose();        

-        clientSynchChannel.dispose();        

-        syncChannelServer.dispose();

-    }

-

-    private void createAsynchObjects(String bindURI) throws IOException, URISyntaxException, InterruptedException {

-        asyncChannelServer = factory.bindAsyncChannel(new URI(bindURI));

-        final CountDownLatch accepted = new CountDownLatch(1);

-        asyncChannelServer.setAcceptListener(new AcceptListener() {

-            public void onAccept(Channel channel) {

-                serverAsyncChannel = SyncToAsyncChannel.adapt(channel);

-                channel.dispose();

-                accepted.countDown();

-            }

-            public void onAcceptError(IOException error) {

-                error.printStackTrace();

-            }

-        });

-        asyncChannelServer.start();

-        clientAsyncChannel = factory.openAsyncChannel(asyncChannelServer.getConnectURI());

-        accepted.await(1000*10, TimeUnit.MILLISECONDS);

-        clientAsyncChannel.dispose();        

-        asyncChannelServer.dispose();

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import junit.framework.TestCase;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelFactory;
+import org.apache.activeio.adapter.AsyncToSyncChannel;
+import org.apache.activeio.adapter.SyncToAsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.async.nio.NIOAsyncChannel;
+import org.apache.activeio.packet.async.nio.NIOAsyncChannelServer;
+import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelPipe;
+import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.activeio.packet.sync.nio.NIOSyncChannel;
+import org.apache.activeio.packet.sync.nio.NIOSyncChannelServer;
+import org.apache.activeio.packet.sync.socket.SocketSyncChannel;
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelServer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ */
+public class ChannelFactoryTest extends TestCase {
+
+    static final Log log = LogFactory.getLog(ChannelFactoryTest.class);
+    static boolean aioDisabled = System.getProperty("disable.aio.tests", "false").equals("true");
+
+    ChannelFactory factory = new ChannelFactory();
+
+    private SyncChannelServer syncChannelServer;
+    private SyncChannel clientSynchChannel;
+    private SyncChannel serverSynchChannel;
+
+    private AsyncChannelServer asyncChannelServer;
+    private AsyncChannel clientAsyncChannel;
+    private AsyncChannel serverAsyncChannel;
+    
+    protected void setUp() throws Exception {
+        log.info("Running: "+getName());
+    }
+
+    public void testSocket() throws IOException, URISyntaxException, InterruptedException {
+        
+        createSynchObjects("socket://localhost:0");
+        assertNotNull( syncChannelServer.getAdapter(SocketSyncChannelServer.class) );
+        assertNotNull( clientSynchChannel.getAdapter(SocketSyncChannel.class) );
+        assertNotNull( serverSynchChannel.getAdapter(SocketSyncChannel.class) );
+        
+        createAsynchObjects("socket://localhost:0");
+        assertNotNull( asyncChannelServer.getAdapter(SocketSyncChannelServer.class) );
+        assertNotNull( clientAsyncChannel.getAdapter(SocketSyncChannel.class) );
+        assertNotNull( serverAsyncChannel.getAdapter(SocketSyncChannel.class) );
+        
+    }
+
+    public void testNIO() throws IOException, URISyntaxException, InterruptedException {
+        
+        createSynchObjects("nio://localhost:0");
+        assertNotNull( syncChannelServer.getAdapter(NIOSyncChannelServer.class) );
+        assertNotNull( clientSynchChannel.getAdapter(NIOSyncChannel.class) );
+        assertNotNull( serverSynchChannel.getAdapter(NIOSyncChannel.class) );
+        
+        createAsynchObjects("nio://localhost:0");
+        assertNotNull( asyncChannelServer.getAdapter(NIOAsyncChannelServer.class) );
+        assertNotNull( clientAsyncChannel.getAdapter(NIOAsyncChannel.class) );
+        assertNotNull( serverAsyncChannel.getAdapter(NIOAsyncChannel.class) );
+        
+    }    
+
+    public void testVMPipe() throws IOException, URISyntaxException, InterruptedException {
+        
+        createSynchObjects("vmpipe://localhost");
+        assertNotNull( syncChannelServer.getAdapter(VMPipeAsyncChannelServer.class) );
+        assertNotNull( clientSynchChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );
+        assertNotNull( serverSynchChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );
+        
+        createAsynchObjects("vmpipe://localhost");
+        assertNotNull( asyncChannelServer.getAdapter(VMPipeAsyncChannelServer.class) );
+        assertNotNull( clientAsyncChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );
+        assertNotNull( serverAsyncChannel.getAdapter(VMPipeAsyncChannelPipe.PipeChannel.class) );
+        
+    }    
+    
+    private void createSynchObjects(String bindURI) throws IOException, URISyntaxException {
+        syncChannelServer = factory.bindSyncChannel(new URI(bindURI));
+        syncChannelServer.start();
+        clientSynchChannel = factory.openSyncChannel(syncChannelServer.getConnectURI());
+        serverSynchChannel = AsyncToSyncChannel.adapt( syncChannelServer.accept(1000*5) );
+        serverSynchChannel.dispose();        
+        clientSynchChannel.dispose();        
+        syncChannelServer.dispose();
+    }
+
+    private void createAsynchObjects(String bindURI) throws IOException, URISyntaxException, InterruptedException {
+        asyncChannelServer = factory.bindAsyncChannel(new URI(bindURI));
+        final CountDownLatch accepted = new CountDownLatch(1);
+        asyncChannelServer.setAcceptListener(new AcceptListener() {
+            public void onAccept(Channel channel) {
+                serverAsyncChannel = SyncToAsyncChannel.adapt(channel);
+                channel.dispose();
+                accepted.countDown();
+            }
+            public void onAcceptError(IOException error) {
+                error.printStackTrace();
+            }
+        });
+        asyncChannelServer.start();
+        clientAsyncChannel = factory.openAsyncChannel(asyncChannelServer.getConnectURI());
+        accepted.await(1000*10, TimeUnit.MILLISECONDS);
+        clientAsyncChannel.dispose();        
+        asyncChannelServer.dispose();
+    }
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/PacketDataTest.java b/activeio-core/src/test/java/org/apache/activeio/PacketDataTest.java
index a44726e..1085e62 100644
--- a/activeio-core/src/test/java/org/apache/activeio/PacketDataTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/PacketDataTest.java
@@ -1,44 +1,44 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio;

-

-import java.io.IOException;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.PacketData;

-

-import junit.framework.TestCase;

-

-/**

- */

-public class PacketDataTest extends TestCase {

-

-    ByteArrayPacket packet = new ByteArrayPacket(new byte[200]);

-    PacketData data = new PacketData(packet);

-    

-    public void testInteger() throws IOException {

-        data.writeInt(Integer.MAX_VALUE);

-        data.writeInt(Integer.MIN_VALUE);

-        data.writeInt(551);

-        

-        packet.flip();

-        assertEquals(Integer.MAX_VALUE, data.readInt());

-        assertEquals(Integer.MIN_VALUE, data.readInt());      

-        assertEquals(551, data.readInt());      

-    }

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio;
+
+import java.io.IOException;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.PacketData;
+
+import junit.framework.TestCase;
+
+/**
+ */
+public class PacketDataTest extends TestCase {
+
+    ByteArrayPacket packet = new ByteArrayPacket(new byte[200]);
+    PacketData data = new PacketData(packet);
+    
+    public void testInteger() throws IOException {
+        data.writeInt(Integer.MAX_VALUE);
+        data.writeInt(Integer.MIN_VALUE);
+        data.writeInt(551);
+        
+        packet.flip();
+        assertEquals(Integer.MAX_VALUE, data.readInt());
+        assertEquals(Integer.MIN_VALUE, data.readInt());      
+        assertEquals(551, data.readInt());      
+    }
+    
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/journal/JournalPerfToolSupport.java b/activeio-core/src/test/java/org/apache/activeio/journal/JournalPerfToolSupport.java
index a2d67f1..4313f85 100644
--- a/activeio-core/src/test/java/org/apache/activeio/journal/JournalPerfToolSupport.java
+++ b/activeio-core/src/test/java/org/apache/activeio/journal/JournalPerfToolSupport.java
@@ -1,164 +1,164 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal;

-

-import java.io.File;

-import java.io.FileOutputStream;

-import java.io.IOException;

-import java.io.PrintWriter;

-import java.util.Random;

-

-import org.apache.activeio.journal.InvalidRecordLocationException;

-import org.apache.activeio.journal.Journal;

-import org.apache.activeio.journal.JournalEventListener;

-import org.apache.activeio.journal.RecordLocation;

-import org.apache.activeio.packet.ByteArrayPacket;

-

-/**

- * Provides the base class uses to run performance tests against a Journal.

- * Should be subclassed to customize for specific journal implementation.

- * 

- * @version $Revision: 1.1 $

- */

-abstract public class JournalPerfToolSupport implements JournalEventListener {

-

-	private JournalStatsFilter journal;

-	private Random random = new Random();

-	private byte data[];

-	private int workerCount=0;	

-	private PrintWriter statWriter;

-	// Performance test Options

-	

-	// The output goes here:

-	protected File journalDirectory = new File("journal-logs");

-	protected File statCSVFile = new File("stats.csv");;

-

-	// Controls how often we start a new batch of workers.

-	protected int workerIncrement=20;

-	protected long incrementDelay=1000*20;

-	protected boolean verbose=true;

-

-	// Worker configuration.

-	protected int recordSize=1024;

-	protected int syncFrequency=15;	

-	protected int workerThinkTime=100;

-

-    private final class Worker implements Runnable {

-		public void run() {

-			int i=random.nextInt()%syncFrequency;

-			while(true) {

-				boolean sync=false;

-				

-				if( syncFrequency>=0 && (i%syncFrequency)==0 ) {

-					sync=true;

-				}				

-				try {

-					journal.write(new ByteArrayPacket(data), sync);

-					Thread.sleep(workerThinkTime);

-				} catch (Exception e) {

-					e.printStackTrace();

-					return;

-				}

-				i++;						

-			}					

-		}

-	}	

-	

-    /**

-     * @throws IOException

-	 * 

-	 */

-	protected void exec() throws Exception {

-		

-		System.out.println("Client threads write records using: Record Size: "+recordSize+", Sync Frequency: "+syncFrequency+", Worker Think Time: "+workerThinkTime);

-

-		// Create the record and fill it with some values.

-		data = new byte[recordSize];

-		for (int i = 0; i < data.length; i++) {

-			data[i] = (byte)i;

-		}

-		

-		if( statCSVFile!=null ) {

-			statWriter = new PrintWriter(new FileOutputStream(statCSVFile));

-			statWriter.println("Threads,Throughput (k/s),Forcd write latency (ms),Throughput (records/s)");

-		}

-		

-        if( journalDirectory.exists() ) {

-        	deleteDir(journalDirectory);

-        }		

-        journal = new JournalStatsFilter(createJournal()).enableDetailedStats(verbose);

-        journal.setJournalEventListener(this);

-		

-        try {        	

-        	

-        	// Wait a little to see the worker affect the stats.

-        	// Increment the number of workers every few seconds.

-        	while(true) {

-        		System.out.println("Starting "+workerIncrement+" Workers...");

-            	for(int i=0;i <workerIncrement;i++) {

-                	new Thread(new Worker()).start();

-                	workerCount++;

-            	}

-            				

-            	// Wait a little to see the worker affect the stats.

-            	System.out.println("Waiting "+(incrementDelay/1000)+" seconds before next Stat sample.");

-            	Thread.sleep(incrementDelay);

-            	displayStats();

-            	journal.reset();

-        	}

-        	

-        	

-        } finally {

-        	journal.close();

-        }

-	}

-

-	private void displayStats() {		

-		System.out.println("Stats at "+workerCount+" workers.");

-		System.out.println(journal);        	

-		if( statWriter!= null ) {

-			statWriter.println(""+workerCount+","+journal.getThroughputKps()+","+journal.getAvgSyncedLatencyMs()+","+journal.getThroughputRps());

-			statWriter.flush();

-		}

-	}

-

-	/**

-	 * @return

-	 */

-	abstract public Journal createJournal() throws Exception;

-

-	static private void deleteDir(File f) {

-		File[] files = f.listFiles();

-		for (int i = 0; i < files.length; i++) {

-			File file = files[i];

-			file.delete();

-		}

-		f.delete();

-	}

-    

-    

-	public void overflowNotification(RecordLocation safeLocation) {

-		try {

-			System.out.println("Mark set: "+safeLocation);

-			journal.setMark(safeLocation, false);

-		} catch (InvalidRecordLocationException e) {

-			e.printStackTrace();

-		} catch (IOException e) {

-			e.printStackTrace();

-		}		

-	}

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Random;
+
+import org.apache.activeio.journal.InvalidRecordLocationException;
+import org.apache.activeio.journal.Journal;
+import org.apache.activeio.journal.JournalEventListener;
+import org.apache.activeio.journal.RecordLocation;
+import org.apache.activeio.packet.ByteArrayPacket;
+
+/**
+ * Provides the base class uses to run performance tests against a Journal.
+ * Should be subclassed to customize for specific journal implementation.
+ * 
+ * @version $Revision: 1.1 $
+ */
+abstract public class JournalPerfToolSupport implements JournalEventListener {
+
+	private JournalStatsFilter journal;
+	private Random random = new Random();
+	private byte data[];
+	private int workerCount=0;	
+	private PrintWriter statWriter;
+	// Performance test Options
+	
+	// The output goes here:
+	protected File journalDirectory = new File("journal-logs");
+	protected File statCSVFile = new File("stats.csv");;
+
+	// Controls how often we start a new batch of workers.
+	protected int workerIncrement=20;
+	protected long incrementDelay=1000*20;
+	protected boolean verbose=true;
+
+	// Worker configuration.
+	protected int recordSize=1024;
+	protected int syncFrequency=15;	
+	protected int workerThinkTime=100;
+
+    private final class Worker implements Runnable {
+		public void run() {
+			int i=random.nextInt()%syncFrequency;
+			while(true) {
+				boolean sync=false;
+				
+				if( syncFrequency>=0 && (i%syncFrequency)==0 ) {
+					sync=true;
+				}				
+				try {
+					journal.write(new ByteArrayPacket(data), sync);
+					Thread.sleep(workerThinkTime);
+				} catch (Exception e) {
+					e.printStackTrace();
+					return;
+				}
+				i++;						
+			}					
+		}
+	}	
+	
+    /**
+     * @throws IOException
+	 * 
+	 */
+	protected void exec() throws Exception {
+		
+		System.out.println("Client threads write records using: Record Size: "+recordSize+", Sync Frequency: "+syncFrequency+", Worker Think Time: "+workerThinkTime);
+
+		// Create the record and fill it with some values.
+		data = new byte[recordSize];
+		for (int i = 0; i < data.length; i++) {
+			data[i] = (byte)i;
+		}
+		
+		if( statCSVFile!=null ) {
+			statWriter = new PrintWriter(new FileOutputStream(statCSVFile));
+			statWriter.println("Threads,Throughput (k/s),Forcd write latency (ms),Throughput (records/s)");
+		}
+		
+        if( journalDirectory.exists() ) {
+        	deleteDir(journalDirectory);
+        }		
+        journal = new JournalStatsFilter(createJournal()).enableDetailedStats(verbose);
+        journal.setJournalEventListener(this);
+		
+        try {        	
+        	
+        	// Wait a little to see the worker affect the stats.
+        	// Increment the number of workers every few seconds.
+        	while(true) {
+        		System.out.println("Starting "+workerIncrement+" Workers...");
+            	for(int i=0;i <workerIncrement;i++) {
+                	new Thread(new Worker()).start();
+                	workerCount++;
+            	}
+            				
+            	// Wait a little to see the worker affect the stats.
+            	System.out.println("Waiting "+(incrementDelay/1000)+" seconds before next Stat sample.");
+            	Thread.sleep(incrementDelay);
+            	displayStats();
+            	journal.reset();
+        	}
+        	
+        	
+        } finally {
+        	journal.close();
+        }
+	}
+
+	private void displayStats() {		
+		System.out.println("Stats at "+workerCount+" workers.");
+		System.out.println(journal);        	
+		if( statWriter!= null ) {
+			statWriter.println(""+workerCount+","+journal.getThroughputKps()+","+journal.getAvgSyncedLatencyMs()+","+journal.getThroughputRps());
+			statWriter.flush();
+		}
+	}
+
+	/**
+	 * @return
+	 */
+	abstract public Journal createJournal() throws Exception;
+
+	static private void deleteDir(File f) {
+		File[] files = f.listFiles();
+		for (int i = 0; i < files.length; i++) {
+			File file = files[i];
+			file.delete();
+		}
+		f.delete();
+	}
+    
+    
+	public void overflowNotification(RecordLocation safeLocation) {
+		try {
+			System.out.println("Mark set: "+safeLocation);
+			journal.setMark(safeLocation, false);
+		} catch (InvalidRecordLocationException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}		
+	}
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/journal/JournalStatsFilter.java b/activeio-core/src/test/java/org/apache/activeio/journal/JournalStatsFilter.java
index bee2c27..2c2a19f 100644
--- a/activeio-core/src/test/java/org/apache/activeio/journal/JournalStatsFilter.java
+++ b/activeio-core/src/test/java/org/apache/activeio/journal/JournalStatsFilter.java
@@ -1,265 +1,265 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal;

-

-import java.io.IOException;

-import java.io.PrintWriter;

-import java.io.StringWriter;

-

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.stats.CountStatisticImpl;

-import org.apache.activeio.stats.IndentPrinter;

-import org.apache.activeio.stats.TimeStatisticImpl;

-

-/**

- * A Journal filter that captures performance statistics of the filtered Journal.

- * 

- * @version $Revision: 1.1 $

- */

-public class JournalStatsFilter implements Journal {

-	

-	private final TimeStatisticImpl writeLatency = new TimeStatisticImpl("writeLatency", "The amount of time that is spent waiting for a record to be written to the Journal"); 

-	private final CountStatisticImpl writeRecordsCounter = new CountStatisticImpl("writeRecordsCounter","The number of records that have been written by the Journal");

-	private final CountStatisticImpl writeBytesCounter = new CountStatisticImpl("writeBytesCounter","The number of bytes that have been written by the Journal");

-	private final TimeStatisticImpl synchedWriteLatency = new TimeStatisticImpl(writeLatency, "synchedWriteLatency", "The amount of time that is spent waiting for a synch record to be written to the Journal"); 

-	private final TimeStatisticImpl unsynchedWriteLatency = new TimeStatisticImpl(writeLatency, "unsynchedWriteLatency", "The amount of time that is spent waiting for a non synch record to be written to the Journal"); 	

-	private final TimeStatisticImpl readLatency = new TimeStatisticImpl("readLatency", "The amount of time that is spent waiting for a record to be read from the Journal"); 

-	private final CountStatisticImpl readBytesCounter = new CountStatisticImpl("readBytesCounter","The number of bytes that have been read by the Journal");

-	

-	private final Journal next;

-	private boolean detailedStats;

-

-	

-	/**

-	 * Creates a JournalStatsFilter that captures performance information of <code>next</next>. 

-	 * @param next

-	 */

-	public JournalStatsFilter(Journal next) {

-		this.next = next;

-	}

-	

-	/**

-	 * @see org.codehaus.activemq.journal.Journal#write(byte[], boolean)

-	 */

-	public RecordLocation write(Packet data, boolean sync) throws IOException {

-		//writeWaitTimeStat

-		long start = System.currentTimeMillis();

-		RecordLocation answer = next.write(data, sync);

-		long end = System.currentTimeMillis();

-		

-		writeRecordsCounter.increment();

-		writeBytesCounter.add(data.remaining());

-		if( sync )

-			synchedWriteLatency.addTime(end-start);

-		else 

-			unsynchedWriteLatency.addTime(end-start);

-		return answer;

-	}

-

-	/**

-	 * @see org.codehaus.activemq.journal.Journal#read(org.codehaus.activemq.journal.RecordLocation)

-	 */

-	public Packet read(RecordLocation location)

-			throws InvalidRecordLocationException, IOException {

-		

-		long start = System.currentTimeMillis();

-		Packet answer = next.read(location);		

-		long end = System.currentTimeMillis();

-		

-		readBytesCounter.add(answer.remaining());

-		readLatency.addTime(end-start);

-		return answer;

-	}

-

-	/**

-	 * @see org.codehaus.activemq.journal.Journal#setMark(org.codehaus.activemq.journal.RecordLocation, boolean)

-	 */

-	public void setMark(RecordLocation recordLocator, boolean force)

-			throws InvalidRecordLocationException, IOException {

-		next.setMark(recordLocator, force);

-	}

-

-	/**

-	 * @see org.codehaus.activemq.journal.Journal#getMark()

-	 */

-	public RecordLocation getMark() {

-		return next.getMark();

-	}

-

-	/**

-	 * @see org.codehaus.activemq.journal.Journal#close()

-	 */

-	public void close() throws IOException {

-		next.close();

-	}

-	

-	/**

-	 * @see org.codehaus.activemq.journal.Journal#setJournalEventListener(org.codehaus.activemq.journal.JournalEventListener)

-	 */

-	public void setJournalEventListener(JournalEventListener eventListener) {

-	    next.setJournalEventListener(eventListener);

-	}

-

-	/**

-	 * @see org.codehaus.activemq.journal.Journal#getNextRecordLocation(org.codehaus.activemq.journal.RecordLocation)

-	 */

-	public RecordLocation getNextRecordLocation(RecordLocation lastLocation)

-			throws IOException, InvalidRecordLocationException {		

-		return next.getNextRecordLocation(lastLocation);

-	}

-	

-	/**

-	 * Writes the gathered statistics to the <code>out</code> object.

-	 * 

-	 * @param out

-	 */

-    public void dump(IndentPrinter out) {

-        out.printIndent();

-        out.println("Journal Stats {");        

-        out.incrementIndent();

-        out.printIndent();

-        out.println("Throughput           : "+ getThroughputKps() +" k/s and " + getThroughputRps() +" records/s" );

-        out.printIndent();

-        out.println("Latency with force   : "+ getAvgSyncedLatencyMs() +" ms"  );

-        out.printIndent();

-        out.println("Latency without force: "+ getAvgUnSyncedLatencyMs() +" ms"  );

-

-        out.printIndent();

-        out.println("Raw Stats {");

-        out.incrementIndent();

-                

-        out.printIndent();

-        out.println(writeRecordsCounter);

-        out.printIndent();

-        out.println(writeBytesCounter);

-        out.printIndent();

-        out.println(writeLatency);

-        out.incrementIndent();

-        out.printIndent();

-        out.println(synchedWriteLatency);

-        out.printIndent();

-        out.println(unsynchedWriteLatency);

-        out.decrementIndent();

-

-        out.printIndent();

-        out.println(readBytesCounter);

-        

-        out.printIndent();

-        out.println(readLatency);        

-        out.decrementIndent();

-        out.printIndent();

-        out.println("}");

-        

-        out.decrementIndent();

-        out.printIndent();

-        out.println("}");

-

-    }

-

-    /**

-     * Dumps the stats to a String.

-     * 

-     * @see java.lang.Object#toString()

-     */

-	public String toString() {

-		if( detailedStats ) {

-			StringWriter w = new StringWriter();

-			PrintWriter pw = new PrintWriter(w);		

-			dump(new IndentPrinter(pw, "  "));

-			return w.getBuffer().toString();

-		} else {

-			StringWriter w = new StringWriter();

-			PrintWriter pw = new PrintWriter(w);

-			IndentPrinter out = new IndentPrinter(pw, "  ");

-	        out.println("Throughput           : "+ getThroughputKps() +" k/s and " + getThroughputRps() +" records/s");

-	        out.printIndent();

-	        out.println("Latency with force   : "+getAvgSyncedLatencyMs()+" ms"  );

-	        out.printIndent();

-	        out.println("Latency without force: "+getAvgUnSyncedLatencyMs()+" ms"  );

-			return w.getBuffer().toString();			

-		}

-    }

-

-	/**

-	 * @param detailedStats true if details stats should be displayed by <code>toString()</code> and <code>dump</code>

-	 * @return

-	 */

-	public JournalStatsFilter enableDetailedStats(boolean detailedStats) {		

-		this.detailedStats = detailedStats;

-		return this;

-	}

-

-	/**

-	 * Gets the average throughput in k/s.

-	 * 

-	 * @return the average throughput in k/s.

-	 */

-	public double getThroughputKps() {

-		 long totalTime = writeBytesCounter.getLastSampleTime()-writeBytesCounter.getStartTime(); 

-		 return (((double)writeBytesCounter.getCount()/(double)totalTime)/(double)1024)*1000;

-	}

-

-	/**

-	 * Gets the average throughput in records/s.

-	 * 

-	 * @return the average throughput in records/s.

-	 */

-	public double getThroughputRps() {

-		 long totalTime = writeRecordsCounter.getLastSampleTime()-writeRecordsCounter.getStartTime(); 

-		 return (((double)writeRecordsCounter.getCount()/(double)totalTime))*1000;

-	}

-

-	/**

-	 * Gets the average number of writes done per second

-	 * 

-	 * @return the average number of writes in w/s.

-	 */

-	public double getWritesPerSecond() {

-		 return writeLatency.getAveragePerSecond();

-	}

-

-	/**

-	 * Gets the average sync write latency in ms.

-	 * 

-	 * @return the average sync write latency in ms.

-	 */

-	public double getAvgSyncedLatencyMs() {

-		return synchedWriteLatency.getAverageTime();

-	}

-

-	/**

-	 * Gets the average non sync write latency in ms.

-	 * 

-	 * @return the average non sync write latency in ms.

-	 */

-	public double getAvgUnSyncedLatencyMs() {

-		return unsynchedWriteLatency.getAverageTime();

-	}

-	

-	/**

-	 * Resets the stats sample.

-	 */

-	public void reset() {

-		writeLatency.reset(); 

-		writeBytesCounter.reset();

-		writeRecordsCounter.reset();

-		synchedWriteLatency.reset(); 

-		unsynchedWriteLatency.reset(); 	

-		readLatency.reset(); 

-		readBytesCounter.reset();

-	}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.stats.CountStatisticImpl;
+import org.apache.activeio.stats.IndentPrinter;
+import org.apache.activeio.stats.TimeStatisticImpl;
+
+/**
+ * A Journal filter that captures performance statistics of the filtered Journal.
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class JournalStatsFilter implements Journal {
+	
+	private final TimeStatisticImpl writeLatency = new TimeStatisticImpl("writeLatency", "The amount of time that is spent waiting for a record to be written to the Journal"); 
+	private final CountStatisticImpl writeRecordsCounter = new CountStatisticImpl("writeRecordsCounter","The number of records that have been written by the Journal");
+	private final CountStatisticImpl writeBytesCounter = new CountStatisticImpl("writeBytesCounter","The number of bytes that have been written by the Journal");
+	private final TimeStatisticImpl synchedWriteLatency = new TimeStatisticImpl(writeLatency, "synchedWriteLatency", "The amount of time that is spent waiting for a synch record to be written to the Journal"); 
+	private final TimeStatisticImpl unsynchedWriteLatency = new TimeStatisticImpl(writeLatency, "unsynchedWriteLatency", "The amount of time that is spent waiting for a non synch record to be written to the Journal"); 	
+	private final TimeStatisticImpl readLatency = new TimeStatisticImpl("readLatency", "The amount of time that is spent waiting for a record to be read from the Journal"); 
+	private final CountStatisticImpl readBytesCounter = new CountStatisticImpl("readBytesCounter","The number of bytes that have been read by the Journal");
+	
+	private final Journal next;
+	private boolean detailedStats;
+
+	
+	/**
+	 * Creates a JournalStatsFilter that captures performance information of <code>next</next>. 
+	 * @param next
+	 */
+	public JournalStatsFilter(Journal next) {
+		this.next = next;
+	}
+	
+	/**
+	 * @see org.codehaus.activemq.journal.Journal#write(byte[], boolean)
+	 */
+	public RecordLocation write(Packet data, boolean sync) throws IOException {
+		//writeWaitTimeStat
+		long start = System.currentTimeMillis();
+		RecordLocation answer = next.write(data, sync);
+		long end = System.currentTimeMillis();
+		
+		writeRecordsCounter.increment();
+		writeBytesCounter.add(data.remaining());
+		if( sync )
+			synchedWriteLatency.addTime(end-start);
+		else 
+			unsynchedWriteLatency.addTime(end-start);
+		return answer;
+	}
+
+	/**
+	 * @see org.codehaus.activemq.journal.Journal#read(org.codehaus.activemq.journal.RecordLocation)
+	 */
+	public Packet read(RecordLocation location)
+			throws InvalidRecordLocationException, IOException {
+		
+		long start = System.currentTimeMillis();
+		Packet answer = next.read(location);		
+		long end = System.currentTimeMillis();
+		
+		readBytesCounter.add(answer.remaining());
+		readLatency.addTime(end-start);
+		return answer;
+	}
+
+	/**
+	 * @see org.codehaus.activemq.journal.Journal#setMark(org.codehaus.activemq.journal.RecordLocation, boolean)
+	 */
+	public void setMark(RecordLocation recordLocator, boolean force)
+			throws InvalidRecordLocationException, IOException {
+		next.setMark(recordLocator, force);
+	}
+
+	/**
+	 * @see org.codehaus.activemq.journal.Journal#getMark()
+	 */
+	public RecordLocation getMark() {
+		return next.getMark();
+	}
+
+	/**
+	 * @see org.codehaus.activemq.journal.Journal#close()
+	 */
+	public void close() throws IOException {
+		next.close();
+	}
+	
+	/**
+	 * @see org.codehaus.activemq.journal.Journal#setJournalEventListener(org.codehaus.activemq.journal.JournalEventListener)
+	 */
+	public void setJournalEventListener(JournalEventListener eventListener) {
+	    next.setJournalEventListener(eventListener);
+	}
+
+	/**
+	 * @see org.codehaus.activemq.journal.Journal#getNextRecordLocation(org.codehaus.activemq.journal.RecordLocation)
+	 */
+	public RecordLocation getNextRecordLocation(RecordLocation lastLocation)
+			throws IOException, InvalidRecordLocationException {		
+		return next.getNextRecordLocation(lastLocation);
+	}
+	
+	/**
+	 * Writes the gathered statistics to the <code>out</code> object.
+	 * 
+	 * @param out
+	 */
+    public void dump(IndentPrinter out) {
+        out.printIndent();
+        out.println("Journal Stats {");        
+        out.incrementIndent();
+        out.printIndent();
+        out.println("Throughput           : "+ getThroughputKps() +" k/s and " + getThroughputRps() +" records/s" );
+        out.printIndent();
+        out.println("Latency with force   : "+ getAvgSyncedLatencyMs() +" ms"  );
+        out.printIndent();
+        out.println("Latency without force: "+ getAvgUnSyncedLatencyMs() +" ms"  );
+
+        out.printIndent();
+        out.println("Raw Stats {");
+        out.incrementIndent();
+                
+        out.printIndent();
+        out.println(writeRecordsCounter);
+        out.printIndent();
+        out.println(writeBytesCounter);
+        out.printIndent();
+        out.println(writeLatency);
+        out.incrementIndent();
+        out.printIndent();
+        out.println(synchedWriteLatency);
+        out.printIndent();
+        out.println(unsynchedWriteLatency);
+        out.decrementIndent();
+
+        out.printIndent();
+        out.println(readBytesCounter);
+        
+        out.printIndent();
+        out.println(readLatency);        
+        out.decrementIndent();
+        out.printIndent();
+        out.println("}");
+        
+        out.decrementIndent();
+        out.printIndent();
+        out.println("}");
+
+    }
+
+    /**
+     * Dumps the stats to a String.
+     * 
+     * @see java.lang.Object#toString()
+     */
+	public String toString() {
+		if( detailedStats ) {
+			StringWriter w = new StringWriter();
+			PrintWriter pw = new PrintWriter(w);		
+			dump(new IndentPrinter(pw, "  "));
+			return w.getBuffer().toString();
+		} else {
+			StringWriter w = new StringWriter();
+			PrintWriter pw = new PrintWriter(w);
+			IndentPrinter out = new IndentPrinter(pw, "  ");
+	        out.println("Throughput           : "+ getThroughputKps() +" k/s and " + getThroughputRps() +" records/s");
+	        out.printIndent();
+	        out.println("Latency with force   : "+getAvgSyncedLatencyMs()+" ms"  );
+	        out.printIndent();
+	        out.println("Latency without force: "+getAvgUnSyncedLatencyMs()+" ms"  );
+			return w.getBuffer().toString();			
+		}
+    }
+
+	/**
+	 * @param detailedStats true if details stats should be displayed by <code>toString()</code> and <code>dump</code>
+	 * @return
+	 */
+	public JournalStatsFilter enableDetailedStats(boolean detailedStats) {		
+		this.detailedStats = detailedStats;
+		return this;
+	}
+
+	/**
+	 * Gets the average throughput in k/s.
+	 * 
+	 * @return the average throughput in k/s.
+	 */
+	public double getThroughputKps() {
+		 long totalTime = writeBytesCounter.getLastSampleTime()-writeBytesCounter.getStartTime(); 
+		 return (((double)writeBytesCounter.getCount()/(double)totalTime)/(double)1024)*1000;
+	}
+
+	/**
+	 * Gets the average throughput in records/s.
+	 * 
+	 * @return the average throughput in records/s.
+	 */
+	public double getThroughputRps() {
+		 long totalTime = writeRecordsCounter.getLastSampleTime()-writeRecordsCounter.getStartTime(); 
+		 return (((double)writeRecordsCounter.getCount()/(double)totalTime))*1000;
+	}
+
+	/**
+	 * Gets the average number of writes done per second
+	 * 
+	 * @return the average number of writes in w/s.
+	 */
+	public double getWritesPerSecond() {
+		 return writeLatency.getAveragePerSecond();
+	}
+
+	/**
+	 * Gets the average sync write latency in ms.
+	 * 
+	 * @return the average sync write latency in ms.
+	 */
+	public double getAvgSyncedLatencyMs() {
+		return synchedWriteLatency.getAverageTime();
+	}
+
+	/**
+	 * Gets the average non sync write latency in ms.
+	 * 
+	 * @return the average non sync write latency in ms.
+	 */
+	public double getAvgUnSyncedLatencyMs() {
+		return unsynchedWriteLatency.getAverageTime();
+	}
+	
+	/**
+	 * Resets the stats sample.
+	 */
+	public void reset() {
+		writeLatency.reset(); 
+		writeBytesCounter.reset();
+		writeRecordsCounter.reset();
+		synchedWriteLatency.reset(); 
+		unsynchedWriteLatency.reset(); 	
+		readLatency.reset(); 
+		readBytesCounter.reset();
+	}
 }
\ No newline at end of file
diff --git a/activeio-core/src/test/java/org/apache/activeio/journal/active/DataStruturesTest.java b/activeio-core/src/test/java/org/apache/activeio/journal/active/DataStruturesTest.java
index 1c781ea..77c59d8 100644
--- a/activeio-core/src/test/java/org/apache/activeio/journal/active/DataStruturesTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/journal/active/DataStruturesTest.java
@@ -1,53 +1,53 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.IOException;

-import java.util.ArrayList;

-import java.util.Collections;

-

-import org.apache.activeio.journal.active.Location;

-

-import junit.framework.TestCase;

-

-/**

- * Tests the data structures used JournalImpl

- * 

- * @version $Revision: 1.1 $

- */

-public class DataStruturesTest extends TestCase {

-        

-    synchronized public void testRecordLocationImplComparison() throws IOException {

-        Location l1 = new Location(0, 1); 

-        Location l2 = new Location(0, 2);

-        Location l3 = new Location(0, 3);

-

-        assertTrue( l1.compareTo(l2)<0 );

-        

-        // Sort them using a list.  Put them in the wrong order.

-        ArrayList l = new ArrayList();

-        l.add(l2);

-        l.add(l3);

-        l.add(l1);        

-        Collections.sort(l);

-        

-        // Did they get sorted to the correct order?

-        assertSame( l.get(0), l1 );

-        assertSame( l.get(1), l2 );

-        assertSame( l.get(2), l3 );

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+
+import org.apache.activeio.journal.active.Location;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the data structures used JournalImpl
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class DataStruturesTest extends TestCase {
+        
+    synchronized public void testRecordLocationImplComparison() throws IOException {
+        Location l1 = new Location(0, 1); 
+        Location l2 = new Location(0, 2);
+        Location l3 = new Location(0, 3);
+
+        assertTrue( l1.compareTo(l2)<0 );
+        
+        // Sort them using a list.  Put them in the wrong order.
+        ArrayList l = new ArrayList();
+        l.add(l2);
+        l.add(l3);
+        l.add(l1);        
+        Collections.sort(l);
+        
+        // Did they get sorted to the correct order?
+        assertSame( l.get(0), l1 );
+        assertSame( l.get(1), l2 );
+        assertSame( l.get(2), l3 );
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalImplTest.java b/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalImplTest.java
index 0bb6656..03e2e47 100644
--- a/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalImplTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalImplTest.java
@@ -1,168 +1,168 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.File;

-import java.io.IOException;

-

-import junit.framework.TestCase;

-

-import org.apache.activeio.journal.InvalidRecordLocationException;

-import org.apache.activeio.journal.Journal;

-import org.apache.activeio.journal.RecordLocation;

-import org.apache.activeio.journal.active.JournalImpl;

-import org.apache.activeio.journal.active.Location;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.commons.logging.Log;

-import org.apache.commons.logging.LogFactory;

-

-/**

- * Tests the JournalImpl

- * 

- * @version $Revision: 1.1 $

- */

-public class JournalImplTest extends TestCase {

-

-    Log log = LogFactory.getLog(JournalImplTest.class);

-	

-    int size = 1024*10;

-    int logFileCount=2;

-    File logDirectory = new File("test-logfile");

-	private Journal journal;

-    

-    /**

-     * @see junit.framework.TestCase#setUp()

-     */

-    protected void setUp() throws Exception {

-        if( logDirectory.exists() ) {

-        	deleteDir(logDirectory);

-        }

-        assertTrue("Could not delete directory: "+logDirectory.getCanonicalPath(), !logDirectory.exists() );

-        journal = new JournalImpl(logDirectory,logFileCount, size, logDirectory);

-    }

-

-    /**

-	 */

-	private void deleteDir(File f) {

-		File[] files = f.listFiles();

-		for (int i = 0; i < files.length; i++) {

-			File file = files[i];

-			file.delete();

-		}

-		f.delete();

-	}

-

-	protected void tearDown() throws Exception {

-		journal.close();

-        if( logDirectory.exists() )

-        	deleteDir(logDirectory);

-        //assertTrue( !logDirectory.exists() );

-    }

-    

-    public void testLogFileCreation() throws IOException {

-        	RecordLocation mark = journal.getMark();

-        	assertNull(mark);

-    }

-    

-    public void testAppendAndRead() throws InvalidRecordLocationException, InterruptedException, IOException {

-    	

-        Packet data1 = createPacket("Hello World 1");

-    	RecordLocation location1 = journal.write( data1, false);

-    	Packet data2 = createPacket("Hello World 2");

-    	RecordLocation location2 = journal.write( data2, false);

-    	Packet data3  = createPacket("Hello World 3");

-    	RecordLocation location3 = journal.write( data3, false);

-    	

-    	// Now see if we can read that data.

-    	Packet data;

-    	data = journal.read(location2);

-    	assertEquals( data2, data);

-    	data = journal.read(location1);

-    	assertEquals( data1, data);

-    	data = journal.read(location3);

-    	assertEquals( data3, data);

-    	

-    	// Can we cursor the data?

-    	RecordLocation l=journal.getNextRecordLocation(null);

-    	assertEquals(0, l.compareTo(location1));

-    	data = journal.read(l);

-    	assertEquals( data1, data);

-

-    	l=journal.getNextRecordLocation(l);

-    	assertEquals(0, l.compareTo(location2));

-    	data = journal.read(l);

-    	assertEquals( data2, data);

-

-    	l=journal.getNextRecordLocation(l);

-    	assertEquals(0, l.compareTo(location3));

-    	data = journal.read(l);

-    	assertEquals( data3, data);

-    	

-    	l=journal.getNextRecordLocation(l);

-    	assertNull(l);

-    	

-    	log.info(journal);

-    }

-

-    public void testCanReadFromArchivedLogFile() throws InvalidRecordLocationException, InterruptedException, IOException {

-        

-        Packet data1 = createPacket("Hello World 1");

-        RecordLocation location1 = journal.write( data1, false);

-        

-        Location  pos;

-        do {

-            

-            Packet p = createPacket("<<<data>>>");

-            pos = (Location) journal.write( p, false);

-            journal.setMark(pos, false);

-            

-        } while( pos.getLogFileId() < 5 );

-        

-        // Now see if we can read that first packet.

-        Packet data;

-        data = journal.read(location1);

-        assertEquals( data1, data);

-        

-    }

-

-    /**

-     * @param string

-     * @return

-     */

-    private Packet createPacket(String string) {

-        return new ByteArrayPacket(string.getBytes());

-    }

-

-    public static void assertEquals(Packet arg0, Packet arg1) {

-        assertEquals(arg0.sliceAsBytes(), arg1.sliceAsBytes());

-    }

-    

-    public static void assertEquals(byte[] arg0, byte[] arg1) {

-    	if( arg0==null ^ arg1==null )

-    		fail("Not equal: "+arg0+" != "+arg1);

-    	if( arg0==null )

-    		return;

-    	if( arg0.length!=arg1.length)

-    		fail("Array lenght not equal: "+arg0.length+" != "+arg1.length);

-    	for( int i=0; i<arg0.length;i++) {

-    		if( arg0[i]!= arg1[i]) {

-        		fail("Array item not equal at index "+i+": "+arg0[i]+" != "+arg1[i]);

-    		}

-    	}

-	}

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.File;
+import java.io.IOException;
+
+import junit.framework.TestCase;
+
+import org.apache.activeio.journal.InvalidRecordLocationException;
+import org.apache.activeio.journal.Journal;
+import org.apache.activeio.journal.RecordLocation;
+import org.apache.activeio.journal.active.JournalImpl;
+import org.apache.activeio.journal.active.Location;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Tests the JournalImpl
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class JournalImplTest extends TestCase {
+
+    Log log = LogFactory.getLog(JournalImplTest.class);
+	
+    int size = 1024*10;
+    int logFileCount=2;
+    File logDirectory = new File("test-logfile");
+	private Journal journal;
+    
+    /**
+     * @see junit.framework.TestCase#setUp()
+     */
+    protected void setUp() throws Exception {
+        if( logDirectory.exists() ) {
+        	deleteDir(logDirectory);
+        }
+        assertTrue("Could not delete directory: "+logDirectory.getCanonicalPath(), !logDirectory.exists() );
+        journal = new JournalImpl(logDirectory,logFileCount, size, logDirectory);
+    }
+
+    /**
+	 */
+	private void deleteDir(File f) {
+		File[] files = f.listFiles();
+		for (int i = 0; i < files.length; i++) {
+			File file = files[i];
+			file.delete();
+		}
+		f.delete();
+	}
+
+	protected void tearDown() throws Exception {
+		journal.close();
+        if( logDirectory.exists() )
+        	deleteDir(logDirectory);
+        //assertTrue( !logDirectory.exists() );
+    }
+    
+    public void testLogFileCreation() throws IOException {
+        	RecordLocation mark = journal.getMark();
+        	assertNull(mark);
+    }
+    
+    public void testAppendAndRead() throws InvalidRecordLocationException, InterruptedException, IOException {
+    	
+        Packet data1 = createPacket("Hello World 1");
+    	RecordLocation location1 = journal.write( data1, false);
+    	Packet data2 = createPacket("Hello World 2");
+    	RecordLocation location2 = journal.write( data2, false);
+    	Packet data3  = createPacket("Hello World 3");
+    	RecordLocation location3 = journal.write( data3, false);
+    	
+    	// Now see if we can read that data.
+    	Packet data;
+    	data = journal.read(location2);
+    	assertEquals( data2, data);
+    	data = journal.read(location1);
+    	assertEquals( data1, data);
+    	data = journal.read(location3);
+    	assertEquals( data3, data);
+    	
+    	// Can we cursor the data?
+    	RecordLocation l=journal.getNextRecordLocation(null);
+    	assertEquals(0, l.compareTo(location1));
+    	data = journal.read(l);
+    	assertEquals( data1, data);
+
+    	l=journal.getNextRecordLocation(l);
+    	assertEquals(0, l.compareTo(location2));
+    	data = journal.read(l);
+    	assertEquals( data2, data);
+
+    	l=journal.getNextRecordLocation(l);
+    	assertEquals(0, l.compareTo(location3));
+    	data = journal.read(l);
+    	assertEquals( data3, data);
+    	
+    	l=journal.getNextRecordLocation(l);
+    	assertNull(l);
+    	
+    	log.info(journal);
+    }
+
+    public void testCanReadFromArchivedLogFile() throws InvalidRecordLocationException, InterruptedException, IOException {
+        
+        Packet data1 = createPacket("Hello World 1");
+        RecordLocation location1 = journal.write( data1, false);
+        
+        Location  pos;
+        do {
+            
+            Packet p = createPacket("<<<data>>>");
+            pos = (Location) journal.write( p, false);
+            journal.setMark(pos, false);
+            
+        } while( pos.getLogFileId() < 5 );
+        
+        // Now see if we can read that first packet.
+        Packet data;
+        data = journal.read(location1);
+        assertEquals( data1, data);
+        
+    }
+
+    /**
+     * @param string
+     * @return
+     */
+    private Packet createPacket(String string) {
+        return new ByteArrayPacket(string.getBytes());
+    }
+
+    public static void assertEquals(Packet arg0, Packet arg1) {
+        assertEquals(arg0.sliceAsBytes(), arg1.sliceAsBytes());
+    }
+    
+    public static void assertEquals(byte[] arg0, byte[] arg1) {
+    	if( arg0==null ^ arg1==null )
+    		fail("Not equal: "+arg0+" != "+arg1);
+    	if( arg0==null )
+    		return;
+    	if( arg0.length!=arg1.length)
+    		fail("Array lenght not equal: "+arg0.length+" != "+arg1.length);
+    	for( int i=0; i<arg0.length;i++) {
+    		if( arg0[i]!= arg1[i]) {
+        		fail("Array item not equal at index "+i+": "+arg0[i]+" != "+arg1[i]);
+    		}
+    	}
+	}
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalPerfTool.java b/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalPerfTool.java
index df79b4b..5b3bb0b 100644
--- a/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalPerfTool.java
+++ b/activeio-core/src/test/java/org/apache/activeio/journal/active/JournalPerfTool.java
@@ -1,76 +1,76 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.File;

-import java.io.IOException;

-

-import org.apache.activeio.journal.Journal;

-import org.apache.activeio.journal.JournalPerfToolSupport;

-import org.apache.activeio.journal.active.JournalImpl;

-

-/**

- * A Performance statistics gathering tool for the JournalImpl based Journal.

- * 

- * @version $Revision: 1.1 $

- */

-public class JournalPerfTool extends JournalPerfToolSupport {

-	

-	private int logFileSize = 1024*1000*5;

-    private int logFileCount = 4;

-	

-	public static void main(String[] args) throws Exception {

-		JournalPerfTool tool = new JournalPerfTool();

-		if( args.length > 0 ) {

-			tool.journalDirectory = new File(args[0]);

-		}

-		if( args.length > 1 ) {

-			tool.workerIncrement = Integer.parseInt(args[1]);

-		}

-		if( args.length > 2 ) {

-			tool.incrementDelay = Long.parseLong(args[2]);

-		}

-		if( args.length > 3 ) {

-			tool.verbose = Boolean.getBoolean(args[3]);

-		}

-		if( args.length > 4 ) {

-			tool.recordSize = Integer.parseInt(args[4]);

-		}

-		if( args.length > 5 ) {

-			tool.syncFrequency = Integer.parseInt(args[5]);

-		}

-		if( args.length > 6 ) {

-			tool.workerThinkTime = Integer.parseInt(args[6]);

-		}

-		if( args.length > 7 ) {

-			tool.logFileCount = Integer.parseInt(args[7]);

-		}

-		if( args.length > 8 ) {

-			tool.logFileSize = Integer.parseInt(args[8]);

-		}

-		tool.exec();

-	}

-

-	/**

-	 * @throws IOException

-	 * @see org.apache.activeio.journal.JournalPerfToolSupport#createJournal()

-	 */

-	public Journal createJournal() throws IOException {

-		return new JournalImpl( this.journalDirectory, logFileCount, logFileSize);

-	}

-	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.activeio.journal.Journal;
+import org.apache.activeio.journal.JournalPerfToolSupport;
+import org.apache.activeio.journal.active.JournalImpl;
+
+/**
+ * A Performance statistics gathering tool for the JournalImpl based Journal.
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class JournalPerfTool extends JournalPerfToolSupport {
+	
+	private int logFileSize = 1024*1000*5;
+    private int logFileCount = 4;
+	
+	public static void main(String[] args) throws Exception {
+		JournalPerfTool tool = new JournalPerfTool();
+		if( args.length > 0 ) {
+			tool.journalDirectory = new File(args[0]);
+		}
+		if( args.length > 1 ) {
+			tool.workerIncrement = Integer.parseInt(args[1]);
+		}
+		if( args.length > 2 ) {
+			tool.incrementDelay = Long.parseLong(args[2]);
+		}
+		if( args.length > 3 ) {
+			tool.verbose = Boolean.getBoolean(args[3]);
+		}
+		if( args.length > 4 ) {
+			tool.recordSize = Integer.parseInt(args[4]);
+		}
+		if( args.length > 5 ) {
+			tool.syncFrequency = Integer.parseInt(args[5]);
+		}
+		if( args.length > 6 ) {
+			tool.workerThinkTime = Integer.parseInt(args[6]);
+		}
+		if( args.length > 7 ) {
+			tool.logFileCount = Integer.parseInt(args[7]);
+		}
+		if( args.length > 8 ) {
+			tool.logFileSize = Integer.parseInt(args[8]);
+		}
+		tool.exec();
+	}
+
+	/**
+	 * @throws IOException
+	 * @see org.apache.activeio.journal.JournalPerfToolSupport#createJournal()
+	 */
+	public Journal createJournal() throws IOException {
+		return new JournalImpl( this.journalDirectory, logFileCount, logFileSize);
+	}
+	
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/journal/active/LogFileManagerTest.java b/activeio-core/src/test/java/org/apache/activeio/journal/active/LogFileManagerTest.java
index ad01322..a611205 100644
--- a/activeio-core/src/test/java/org/apache/activeio/journal/active/LogFileManagerTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/journal/active/LogFileManagerTest.java
@@ -1,134 +1,134 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.active;

-

-import java.io.File;

-import java.io.IOException;

-import java.nio.ByteBuffer;

-

-import junit.framework.TestCase;

-

-import org.apache.activeio.journal.InvalidRecordLocationException;

-import org.apache.activeio.journal.active.BatchedWrite;

-import org.apache.activeio.journal.active.Location;

-import org.apache.activeio.journal.active.LogFileManager;

-import org.apache.activeio.journal.active.Record;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.ByteBufferPacket;

-

-/**

- * Tests the LogFile used by JournalImpl

- * 

- * @version $Revision: 1.1 $

- */

-public class LogFileManagerTest extends TestCase {

-

-    int size = 1024 * 512;

-

-    int logFileCount = 4;

-

-    File logDirectory = new File("test-logfile");

-

-    private LogFileManager logFile;

-

-    /**

-     * @see junit.framework.TestCase#setUp()

-     */

-    protected void setUp() throws Exception {

-        if (logDirectory.exists()) {

-            deleteDir(logDirectory);

-        }

-        assertTrue(!logDirectory.exists());

-        logFile = new LogFileManager(logDirectory, logFileCount, size, null);

-    }

-

-    /**

-     */

-    private void deleteDir(File f) {

-        File[] files = f.listFiles();

-        for (int i = 0; i < files.length; i++) {

-            File file = files[i];

-            file.delete();

-        }

-        f.delete();

-    }

-

-    protected void tearDown() throws Exception {

-        logFile.dispose();

-        if (logDirectory.exists())

-            deleteDir(logDirectory);

-        assertTrue(!logDirectory.exists());

-    }

-

-    public void testLogFileCreation() throws IOException {

-        assertTrue(logFile.canActivateNextLogFile());

-        assertEquals(null,logFile.getFirstActiveLogLocation());

-        assertNull(logFile.getLastMarkedRecordLocation());

-        assertEquals(new Location(0, 0),logFile.getNextAppendLocation());

-    }

-

-    public void testAppendAndRead() throws IOException, InvalidRecordLocationException, InterruptedException {

-

-        System.out.println("Initial:"+logFile.getNextAppendLocation());

-        appendHelloRecord(1001);

-        Location loc2 = logFile.getNextAppendLocation();

-        appendHelloRecord(2002);

-        appendHelloRecord(3003);

-        appendHelloRecord(3004);

-

-        Location loc3 = logFile.getNextDataRecordLocation(loc2);

-        assertTrue(loc3.getLogFileOffset() > loc2.getLogFileOffset());

-        Location loc4 = logFile.getNextDataRecordLocation(loc3);

-        assertTrue(loc4.getLogFileOffset() > loc3.getLogFileOffset());

-

-    }

-

-    public void testRollOver() throws IOException, InvalidRecordLocationException, InterruptedException {

-

-        int lastId = logFile.getNextAppendLocation().getLogFileId();

-        int counter = 0;

-        for (int i = 0; i < logFileCount; i++) {

-            counter += 500;

-            appendHelloRecord(counter);

-            if (i + 1 == logFileCount) {

-                assertFalse(logFile.canActivateNextLogFile());

-            } else {

-                assertTrue(logFile.canActivateNextLogFile());

-                logFile.activateNextLogFile();

-                assertEquals(lastId + 1, logFile.getNextAppendLocation().getLogFileId());

-                lastId = logFile.getNextAppendLocation().getLogFileId();

-            }

-        }

-

-    }

-

-    /**

-     * @param i

-     * @throws IOException

-     * @throws InterruptedException

-     */

-    private void appendHelloRecord(int i) throws IOException, InterruptedException {

-        byte data[] = ("Hello World: " + i).getBytes();

-        Record batchedRecord = new Record(LogFileManager.DATA_RECORD_TYPE, new ByteArrayPacket(data), null);

-        batchedRecord.setLocation(logFile.getNextAppendLocation());

-        

-        BatchedWrite write = new BatchedWrite(new ByteBufferPacket(ByteBuffer.allocate(1024)));

-        write.append(batchedRecord,null, true);

-        write.flip();

-        logFile.append(write);

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.active;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import junit.framework.TestCase;
+
+import org.apache.activeio.journal.InvalidRecordLocationException;
+import org.apache.activeio.journal.active.BatchedWrite;
+import org.apache.activeio.journal.active.Location;
+import org.apache.activeio.journal.active.LogFileManager;
+import org.apache.activeio.journal.active.Record;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.ByteBufferPacket;
+
+/**
+ * Tests the LogFile used by JournalImpl
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class LogFileManagerTest extends TestCase {
+
+    int size = 1024 * 512;
+
+    int logFileCount = 4;
+
+    File logDirectory = new File("test-logfile");
+
+    private LogFileManager logFile;
+
+    /**
+     * @see junit.framework.TestCase#setUp()
+     */
+    protected void setUp() throws Exception {
+        if (logDirectory.exists()) {
+            deleteDir(logDirectory);
+        }
+        assertTrue(!logDirectory.exists());
+        logFile = new LogFileManager(logDirectory, logFileCount, size, null);
+    }
+
+    /**
+     */
+    private void deleteDir(File f) {
+        File[] files = f.listFiles();
+        for (int i = 0; i < files.length; i++) {
+            File file = files[i];
+            file.delete();
+        }
+        f.delete();
+    }
+
+    protected void tearDown() throws Exception {
+        logFile.dispose();
+        if (logDirectory.exists())
+            deleteDir(logDirectory);
+        assertTrue(!logDirectory.exists());
+    }
+
+    public void testLogFileCreation() throws IOException {
+        assertTrue(logFile.canActivateNextLogFile());
+        assertEquals(null,logFile.getFirstActiveLogLocation());
+        assertNull(logFile.getLastMarkedRecordLocation());
+        assertEquals(new Location(0, 0),logFile.getNextAppendLocation());
+    }
+
+    public void testAppendAndRead() throws IOException, InvalidRecordLocationException, InterruptedException {
+
+        System.out.println("Initial:"+logFile.getNextAppendLocation());
+        appendHelloRecord(1001);
+        Location loc2 = logFile.getNextAppendLocation();
+        appendHelloRecord(2002);
+        appendHelloRecord(3003);
+        appendHelloRecord(3004);
+
+        Location loc3 = logFile.getNextDataRecordLocation(loc2);
+        assertTrue(loc3.getLogFileOffset() > loc2.getLogFileOffset());
+        Location loc4 = logFile.getNextDataRecordLocation(loc3);
+        assertTrue(loc4.getLogFileOffset() > loc3.getLogFileOffset());
+
+    }
+
+    public void testRollOver() throws IOException, InvalidRecordLocationException, InterruptedException {
+
+        int lastId = logFile.getNextAppendLocation().getLogFileId();
+        int counter = 0;
+        for (int i = 0; i < logFileCount; i++) {
+            counter += 500;
+            appendHelloRecord(counter);
+            if (i + 1 == logFileCount) {
+                assertFalse(logFile.canActivateNextLogFile());
+            } else {
+                assertTrue(logFile.canActivateNextLogFile());
+                logFile.activateNextLogFile();
+                assertEquals(lastId + 1, logFile.getNextAppendLocation().getLogFileId());
+                lastId = logFile.getNextAppendLocation().getLogFileId();
+            }
+        }
+
+    }
+
+    /**
+     * @param i
+     * @throws IOException
+     * @throws InterruptedException
+     */
+    private void appendHelloRecord(int i) throws IOException, InterruptedException {
+        byte data[] = ("Hello World: " + i).getBytes();
+        Record batchedRecord = new Record(LogFileManager.DATA_RECORD_TYPE, new ByteArrayPacket(data), null);
+        batchedRecord.setLocation(logFile.getNextAppendLocation());
+        
+        BatchedWrite write = new BatchedWrite(new ByteBufferPacket(ByteBuffer.allocate(1024)));
+        write.append(batchedRecord,null, true);
+        write.flip();
+        logFile.append(write);
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/journal/howl/JournalPerfTool.java b/activeio-core/src/test/java/org/apache/activeio/journal/howl/JournalPerfTool.java
index 1f7adeb..65b6e09 100644
--- a/activeio-core/src/test/java/org/apache/activeio/journal/howl/JournalPerfTool.java
+++ b/activeio-core/src/test/java/org/apache/activeio/journal/howl/JournalPerfTool.java
@@ -1,92 +1,92 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.journal.howl;

-

-import java.io.File;

-

-import org.apache.activeio.journal.Journal;

-import org.apache.activeio.journal.JournalPerfToolSupport;

-import org.apache.activeio.journal.howl.HowlJournal;

-import org.objectweb.howl.log.Configuration;

-

-/**

- * A Performance statistics gathering tool for the HOWL based Journal.

- * 

- * @version $Revision: 1.1 $

- */

-public class JournalPerfTool extends JournalPerfToolSupport {

-	

-    private int maxLogFiles=  2;

-	private int bufferSize = 1024*4;

-	private int maxBuffers = 20;

-	private int maxBlocksPerFile = 100;

-	

-	public static void main(String[] args) throws Exception {

-		

-		try {

-			JournalPerfTool tool = new JournalPerfTool();

-			if( args.length > 0 ) {

-				tool.journalDirectory = new File(args[0]);

-			}

-			if( args.length > 1 ) {

-				tool.workerIncrement = Integer.parseInt(args[1]);

-			}

-			if( args.length > 2 ) {

-				tool.incrementDelay = Long.parseLong(args[2]);

-			}

-			if( args.length > 3 ) {

-				tool.verbose = Boolean.getBoolean(args[3]);

-			}

-			if( args.length > 4 ) {

-				tool.recordSize = Integer.parseInt(args[4]);

-			}

-			if( args.length > 5 ) {

-				tool.syncFrequency = Integer.parseInt(args[5]);

-			}

-			if( args.length > 6 ) {

-				tool.workerThinkTime = Integer.parseInt(args[6]);

-			}

-			

-			if( args.length > 7 ) {

-				tool.maxLogFiles = Integer.parseInt(args[7]);

-			}

-			if( args.length > 8 ) {

-				tool.bufferSize = Integer.parseInt(args[8]);

-			}

-			if( args.length > 9 ) {

-				tool.maxBuffers = Integer.parseInt(args[9]);

-			}

-			if( args.length > 10 ) {

-				tool.maxBlocksPerFile = Integer.parseInt(args[10]);

-			}

-			tool.exec();

-		} catch (Throwable e) {

-			e.printStackTrace();

-		}

-	}

-

-	public Journal createJournal() throws Exception {

-		Configuration c = new Configuration();

-		c.setLogFileDir(journalDirectory.getPath());

-		c.setMaxLogFiles(maxLogFiles);

-		c.setBufferSize(bufferSize);

-		c.setMaxBuffers(maxBuffers);

-		c.setMaxBlocksPerFile(maxBlocksPerFile);

-		return new HowlJournal( c );

-	}

-	

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.journal.howl;
+
+import java.io.File;
+
+import org.apache.activeio.journal.Journal;
+import org.apache.activeio.journal.JournalPerfToolSupport;
+import org.apache.activeio.journal.howl.HowlJournal;
+import org.objectweb.howl.log.Configuration;
+
+/**
+ * A Performance statistics gathering tool for the HOWL based Journal.
+ * 
+ * @version $Revision: 1.1 $
+ */
+public class JournalPerfTool extends JournalPerfToolSupport {
+	
+    private int maxLogFiles=  2;
+	private int bufferSize = 1024*4;
+	private int maxBuffers = 20;
+	private int maxBlocksPerFile = 100;
+	
+	public static void main(String[] args) throws Exception {
+		
+		try {
+			JournalPerfTool tool = new JournalPerfTool();
+			if( args.length > 0 ) {
+				tool.journalDirectory = new File(args[0]);
+			}
+			if( args.length > 1 ) {
+				tool.workerIncrement = Integer.parseInt(args[1]);
+			}
+			if( args.length > 2 ) {
+				tool.incrementDelay = Long.parseLong(args[2]);
+			}
+			if( args.length > 3 ) {
+				tool.verbose = Boolean.getBoolean(args[3]);
+			}
+			if( args.length > 4 ) {
+				tool.recordSize = Integer.parseInt(args[4]);
+			}
+			if( args.length > 5 ) {
+				tool.syncFrequency = Integer.parseInt(args[5]);
+			}
+			if( args.length > 6 ) {
+				tool.workerThinkTime = Integer.parseInt(args[6]);
+			}
+			
+			if( args.length > 7 ) {
+				tool.maxLogFiles = Integer.parseInt(args[7]);
+			}
+			if( args.length > 8 ) {
+				tool.bufferSize = Integer.parseInt(args[8]);
+			}
+			if( args.length > 9 ) {
+				tool.maxBuffers = Integer.parseInt(args[9]);
+			}
+			if( args.length > 10 ) {
+				tool.maxBlocksPerFile = Integer.parseInt(args[10]);
+			}
+			tool.exec();
+		} catch (Throwable e) {
+			e.printStackTrace();
+		}
+	}
+
+	public Journal createJournal() throws Exception {
+		Configuration c = new Configuration();
+		c.setLogFileDir(journalDirectory.getPath());
+		c.setMaxLogFiles(maxLogFiles);
+		c.setBufferSize(bufferSize);
+		c.setMaxBuffers(maxBuffers);
+		c.setMaxBlocksPerFile(maxBlocksPerFile);
+		return new HowlJournal( c );
+	}
+	
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/oneport/OnePortAsyncChannelServerTest.java b/activeio-core/src/test/java/org/apache/activeio/oneport/OnePortAsyncChannelServerTest.java
index 142fa70..a6d4afe 100644
--- a/activeio-core/src/test/java/org/apache/activeio/oneport/OnePortAsyncChannelServerTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/oneport/OnePortAsyncChannelServerTest.java
@@ -1,228 +1,228 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport;

-

-import java.io.IOException;

-import java.io.InputStream;

-import java.net.MalformedURLException;

-import java.net.URI;

-import java.net.URISyntaxException;

-import java.net.URL;

-

-import junit.framework.TestCase;

-

-import org.apache.activeio.AcceptListener;

-import org.apache.activeio.Channel;

-import org.apache.activeio.adapter.AsyncToSyncChannel;

-import org.apache.activeio.adapter.SyncToAsyncChannelFactory;

-import org.apache.activeio.oneport.HttpRecognizer;

-import org.apache.activeio.oneport.IIOPRecognizer;

-import org.apache.activeio.oneport.OnePortAsyncChannelServer;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.async.AsyncChannel;

-import org.apache.activeio.packet.async.AsyncChannelFactory;

-import org.apache.activeio.packet.async.AsyncChannelServer;

-import org.apache.activeio.packet.async.FilterAsyncChannelServer;

-import org.apache.activeio.packet.sync.FilterSyncChannel;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;

-import org.apache.activeio.stream.sync.socket.SocketMetadata;

-import org.apache.commons.logging.Log;

-import org.apache.commons.logging.LogFactory;

-

-import edu.emory.mathcs.backport.java.util.concurrent.ArrayBlockingQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;

-import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;

-import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;

-import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor;

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;

-

-/**

- */

-public class OnePortAsyncChannelServerTest extends TestCase {

-

-    static private Log log = LogFactory.getLog(OnePortAsyncChannelServerTest.class);

-    static public AtomicInteger serverPacketCounter = new AtomicInteger(0);

-

-    public OnePortAsyncChannelServer server;

-    public AsyncChannelServer httpServer;

-    public AsyncChannelServer iiopServer;

-    public SocketSyncChannelFactory channelFactory;

-    public BlockingQueue resultSlot = new ArrayBlockingQueue(1);

-

-    public void testIIOPAccept() throws Exception {

-        serverPacketCounter.set(0);

-        hitIIOPServer();

-        String type = (String) resultSlot.poll(10, TimeUnit.SECONDS);

-        assertEquals("IIOP", type);

-        // Verify that a request when through the one port.

-        assertTrue(serverPacketCounter.get()>0);

-    }

-

-    public void testHttpAccept() throws IOException, URISyntaxException, InterruptedException {

-        serverPacketCounter.set(0);

-        hitHttpServer();

-        String type = (String) resultSlot.poll(60, TimeUnit.SECONDS);

-        assertEquals("HTTP", type);

-        // Verify that a request when through the one port.

-        assertTrue(serverPacketCounter.get()>0);

-    }

-

-    protected void hitHttpServer() throws IOException, MalformedURLException {

-        URI connectURI = server.getConnectURI();

-        String url = "http://" + connectURI.getHost() + ":" + connectURI.getPort() + "/index.action";

-        log.info(url);

-        InputStream is = new URL(url).openStream();

-        StringBuffer b = new StringBuffer();

-        int c;

-        while ((c = is.read()) >= 0) {

-            b.append((char) c);

-        }

-

-        log.info("HTTP response: " + b);

-    }

-

-    protected void hitIIOPServer() throws Exception {

-        SyncChannel channel = channelFactory.openSyncChannel(server.getConnectURI());

-        ((SocketMetadata)channel.getAdapter(SocketMetadata.class)).setTcpNoDelay(true);

-        channel.write(new ByteArrayPacket("GIOPcrapcrap".getBytes("UTF-8")));

-        channel.flush();

-        channel.stop();

-    }

-

-    public void testUnknownAccept() throws IOException, URISyntaxException, InterruptedException {

-        SyncChannel channel = channelFactory.openSyncChannel(server.getConnectURI());

-        ((SocketMetadata)channel.getAdapter(SocketMetadata.class)).setTcpNoDelay(true);

-        channel

-                .write(new ByteArrayPacket("Licensed under the Apache License, Version 2.0 (the \"License\")"

-                        .getBytes("UTF-8")));

-        channel.flush();

-        String type = (String) resultSlot.poll(1000 * 5, TimeUnit.MILLISECONDS);

-        assertNull(type);

-        channel.dispose();

-    }

-

-    protected void setUp() throws Exception {

-        channelFactory = new SocketSyncChannelFactory();

-        ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new ThreadFactory(){

-            int count=0;

-            public Thread newThread(Runnable arg0) {

-                return new Thread(arg0, "activeio:"+(count++));

-            }});

-        AsyncChannelFactory factory = SyncToAsyncChannelFactory.adapt(channelFactory,executor);

-

-        AsyncChannelServer cs = factory.bindAsyncChannel(new URI("tcp://localhost:0"));

-        cs = new FilterAsyncChannelServer(cs) {

-            public void onAccept(Channel channel) {

-                SyncChannel syncChannel = AsyncToSyncChannel.adapt(channel);                

-                super.onAccept(new FilterSyncChannel(syncChannel) {

-                    public org.apache.activeio.packet.Packet read(long timeout) throws IOException {

-                        Packet packet = super.read(timeout);

-                        if( packet!=null && packet.hasRemaining() )

-                            serverPacketCounter.incrementAndGet();

-                        return packet;

-                    }

-                });

-            }

-        };

-        

-        server = new OnePortAsyncChannelServer(cs);

-        server.start();

-

-        startHTTPServer();

-        startIIOPServer();

-

-        log.info("Running on: "+server.getConnectURI());

-    }

-

-    /**

-     * @throws IOException

-     * @throws NamingException

-     */

-    protected void startIIOPServer() throws Exception {

-        iiopServer = server.bindAsyncChannel(IIOPRecognizer.IIOP_RECOGNIZER);

-        iiopServer.setAcceptListener(new AcceptListener() {

-            public void onAccept(Channel channel) {

-                try {

-                    log.info("Got a IIOP connection.");

-                    resultSlot.offer("IIOP", 1, TimeUnit.MILLISECONDS);

-                    channel.dispose();

-                } catch (InterruptedException e) {

-                    e.printStackTrace();

-                }

-            }

-

-            public void onAcceptError(IOException error) {

-            }

-        });

-        iiopServer.start();

-    }

-

-    /**

-     * @throws IOException

-     * @throws Exception

-     */

-    protected void startHTTPServer() throws Exception {

-        httpServer = server.bindAsyncChannel(HttpRecognizer.HTTP_RECOGNIZER);

-        httpServer.setAcceptListener(new AcceptListener() {

-            public void onAccept(Channel channel) {

-                try {

-                    log.info("Got a HTTP connection.");

-                    resultSlot.offer("HTTP", 1, TimeUnit.MILLISECONDS);

-

-                    byte data[] = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "\r\n"

-                            + "Hello World").getBytes("UTF-8");

-

-                    ((SocketMetadata)channel.getAdapter(SocketMetadata.class)).setTcpNoDelay(true);

-                    ((AsyncChannel) channel).write(new ByteArrayPacket(data));

-

-                    channel.dispose();

-                } catch (Throwable e) {

-                    e.printStackTrace();

-                }

-            }

-

-            public void onAcceptError(IOException error) {

-            }

-        });

-        httpServer.start();

-    }

-

-    protected void tearDown() throws Exception {

-        stopIIOPServer();

-        stopHTTPServer();

-        server.dispose();

-    }

-

-    /**

-     * @throws InterruptedException

-     * 

-     */

-    protected void stopHTTPServer() throws InterruptedException {

-        httpServer.dispose();

-    }

-

-    /**

-     * @throws Exception

-     * 

-     */

-    protected void stopIIOPServer() throws Exception {

-        iiopServer.dispose();

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+
+import junit.framework.TestCase;
+
+import org.apache.activeio.AcceptListener;
+import org.apache.activeio.Channel;
+import org.apache.activeio.adapter.AsyncToSyncChannel;
+import org.apache.activeio.adapter.SyncToAsyncChannelFactory;
+import org.apache.activeio.oneport.HttpRecognizer;
+import org.apache.activeio.oneport.IIOPRecognizer;
+import org.apache.activeio.oneport.OnePortAsyncChannelServer;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.async.AsyncChannel;
+import org.apache.activeio.packet.async.AsyncChannelFactory;
+import org.apache.activeio.packet.async.AsyncChannelServer;
+import org.apache.activeio.packet.async.FilterAsyncChannelServer;
+import org.apache.activeio.packet.sync.FilterSyncChannel;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;
+import org.apache.activeio.stream.sync.socket.SocketMetadata;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import edu.emory.mathcs.backport.java.util.concurrent.ArrayBlockingQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;
+import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;
+import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;
+import edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor;
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ */
+public class OnePortAsyncChannelServerTest extends TestCase {
+
+    static private Log log = LogFactory.getLog(OnePortAsyncChannelServerTest.class);
+    static public AtomicInteger serverPacketCounter = new AtomicInteger(0);
+
+    public OnePortAsyncChannelServer server;
+    public AsyncChannelServer httpServer;
+    public AsyncChannelServer iiopServer;
+    public SocketSyncChannelFactory channelFactory;
+    public BlockingQueue resultSlot = new ArrayBlockingQueue(1);
+
+    public void testIIOPAccept() throws Exception {
+        serverPacketCounter.set(0);
+        hitIIOPServer();
+        String type = (String) resultSlot.poll(10, TimeUnit.SECONDS);
+        assertEquals("IIOP", type);
+        // Verify that a request when through the one port.
+        assertTrue(serverPacketCounter.get()>0);
+    }
+
+    public void testHttpAccept() throws IOException, URISyntaxException, InterruptedException {
+        serverPacketCounter.set(0);
+        hitHttpServer();
+        String type = (String) resultSlot.poll(60, TimeUnit.SECONDS);
+        assertEquals("HTTP", type);
+        // Verify that a request when through the one port.
+        assertTrue(serverPacketCounter.get()>0);
+    }
+
+    protected void hitHttpServer() throws IOException, MalformedURLException {
+        URI connectURI = server.getConnectURI();
+        String url = "http://" + connectURI.getHost() + ":" + connectURI.getPort() + "/index.action";
+        log.info(url);
+        InputStream is = new URL(url).openStream();
+        StringBuffer b = new StringBuffer();
+        int c;
+        while ((c = is.read()) >= 0) {
+            b.append((char) c);
+        }
+
+        log.info("HTTP response: " + b);
+    }
+
+    protected void hitIIOPServer() throws Exception {
+        SyncChannel channel = channelFactory.openSyncChannel(server.getConnectURI());
+        ((SocketMetadata)channel.getAdapter(SocketMetadata.class)).setTcpNoDelay(true);
+        channel.write(new ByteArrayPacket("GIOPcrapcrap".getBytes("UTF-8")));
+        channel.flush();
+        channel.stop();
+    }
+
+    public void testUnknownAccept() throws IOException, URISyntaxException, InterruptedException {
+        SyncChannel channel = channelFactory.openSyncChannel(server.getConnectURI());
+        ((SocketMetadata)channel.getAdapter(SocketMetadata.class)).setTcpNoDelay(true);
+        channel
+                .write(new ByteArrayPacket("Licensed under the Apache License, Version 2.0 (the \"License\")"
+                        .getBytes("UTF-8")));
+        channel.flush();
+        String type = (String) resultSlot.poll(1000 * 5, TimeUnit.MILLISECONDS);
+        assertNull(type);
+        channel.dispose();
+    }
+
+    protected void setUp() throws Exception {
+        channelFactory = new SocketSyncChannelFactory();
+        ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new ThreadFactory(){
+            int count=0;
+            public Thread newThread(Runnable arg0) {
+                return new Thread(arg0, "activeio:"+(count++));
+            }});
+        AsyncChannelFactory factory = SyncToAsyncChannelFactory.adapt(channelFactory,executor);
+
+        AsyncChannelServer cs = factory.bindAsyncChannel(new URI("tcp://localhost:0"));
+        cs = new FilterAsyncChannelServer(cs) {
+            public void onAccept(Channel channel) {
+                SyncChannel syncChannel = AsyncToSyncChannel.adapt(channel);                
+                super.onAccept(new FilterSyncChannel(syncChannel) {
+                    public org.apache.activeio.packet.Packet read(long timeout) throws IOException {
+                        Packet packet = super.read(timeout);
+                        if( packet!=null && packet.hasRemaining() )
+                            serverPacketCounter.incrementAndGet();
+                        return packet;
+                    }
+                });
+            }
+        };
+        
+        server = new OnePortAsyncChannelServer(cs);
+        server.start();
+
+        startHTTPServer();
+        startIIOPServer();
+
+        log.info("Running on: "+server.getConnectURI());
+    }
+
+    /**
+     * @throws IOException
+     * @throws NamingException
+     */
+    protected void startIIOPServer() throws Exception {
+        iiopServer = server.bindAsyncChannel(IIOPRecognizer.IIOP_RECOGNIZER);
+        iiopServer.setAcceptListener(new AcceptListener() {
+            public void onAccept(Channel channel) {
+                try {
+                    log.info("Got a IIOP connection.");
+                    resultSlot.offer("IIOP", 1, TimeUnit.MILLISECONDS);
+                    channel.dispose();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+
+            public void onAcceptError(IOException error) {
+            }
+        });
+        iiopServer.start();
+    }
+
+    /**
+     * @throws IOException
+     * @throws Exception
+     */
+    protected void startHTTPServer() throws Exception {
+        httpServer = server.bindAsyncChannel(HttpRecognizer.HTTP_RECOGNIZER);
+        httpServer.setAcceptListener(new AcceptListener() {
+            public void onAccept(Channel channel) {
+                try {
+                    log.info("Got a HTTP connection.");
+                    resultSlot.offer("HTTP", 1, TimeUnit.MILLISECONDS);
+
+                    byte data[] = ("HTTP/1.1 200 OK\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "\r\n"
+                            + "Hello World").getBytes("UTF-8");
+
+                    ((SocketMetadata)channel.getAdapter(SocketMetadata.class)).setTcpNoDelay(true);
+                    ((AsyncChannel) channel).write(new ByteArrayPacket(data));
+
+                    channel.dispose();
+                } catch (Throwable e) {
+                    e.printStackTrace();
+                }
+            }
+
+            public void onAcceptError(IOException error) {
+            }
+        });
+        httpServer.start();
+    }
+
+    protected void tearDown() throws Exception {
+        stopIIOPServer();
+        stopHTTPServer();
+        server.dispose();
+    }
+
+    /**
+     * @throws InterruptedException
+     * 
+     */
+    protected void stopHTTPServer() throws InterruptedException {
+        httpServer.dispose();
+    }
+
+    /**
+     * @throws Exception
+     * 
+     */
+    protected void stopIIOPServer() throws Exception {
+        iiopServer.dispose();
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/AppendedPacketTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/AppendedPacketTest.java
index b8ea08c..a8a1811 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/AppendedPacketTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/AppendedPacketTest.java
@@ -1,37 +1,37 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import org.apache.activeio.packet.AppendedPacket;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-

-

-/**

- */

-public class AppendedPacketTest extends PacketTestSupport {

-

-    Packet createTestPacket(int capacity) {

-        int c1 = capacity/2;

-        int c2 = capacity-c1;

-        

-        return AppendedPacket.join(

-                	new ByteArrayPacket(new byte[c1]),

-                	new ByteArrayPacket(new byte[c2]));

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import org.apache.activeio.packet.AppendedPacket;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ */
+public class AppendedPacketTest extends PacketTestSupport {
+
+    Packet createTestPacket(int capacity) {
+        int c1 = capacity/2;
+        int c2 = capacity-c1;
+        
+        return AppendedPacket.join(
+                	new ByteArrayPacket(new byte[c1]),
+                	new ByteArrayPacket(new byte[c2]));
+    }
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/ByteArrayPacketTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/ByteArrayPacketTest.java
index af8ba91..fe34b3c 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/ByteArrayPacketTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/ByteArrayPacketTest.java
@@ -1,31 +1,31 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.Packet;

-

-

-/**

- */

-public class ByteArrayPacketTest extends PacketTestSupport {

-

-    Packet createTestPacket(int capacity) {

-        return new ByteArrayPacket(new byte[capacity]);

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ */
+public class ByteArrayPacketTest extends PacketTestSupport {
+
+    Packet createTestPacket(int capacity) {
+        return new ByteArrayPacket(new byte[capacity]);
+    }
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/ByteBufferPacketTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/ByteBufferPacketTest.java
index 83cae93..ff41ac3 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/ByteBufferPacketTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/ByteBufferPacketTest.java
@@ -1,33 +1,33 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.nio.ByteBuffer;

-

-import org.apache.activeio.packet.ByteBufferPacket;

-import org.apache.activeio.packet.Packet;

-

-

-/**

- */

-public class ByteBufferPacketTest extends PacketTestSupport {

-

-    Packet createTestPacket(int capacity) {

-        return new ByteBufferPacket(ByteBuffer.allocate(capacity));

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.nio.ByteBuffer;
+
+import org.apache.activeio.packet.ByteBufferPacket;
+import org.apache.activeio.packet.Packet;
+
+
+/**
+ */
+public class ByteBufferPacketTest extends PacketTestSupport {
+
+    Packet createTestPacket(int capacity) {
+        return new ByteBufferPacket(ByteBuffer.allocate(capacity));
+    }
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/PacketTestSupport.java b/activeio-core/src/test/java/org/apache/activeio/packet/PacketTestSupport.java
index 1b789f3..4cdb1bd 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/PacketTestSupport.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/PacketTestSupport.java
@@ -1,158 +1,158 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet;

-

-import java.util.Arrays;

-

-import org.apache.activeio.packet.Packet;

-

-import junit.framework.TestCase;

-

-

-/**

- */

-abstract public class PacketTestSupport extends TestCase {

-    abstract Packet createTestPacket(int capacity);

-    

-    public void testInit() {

-        Packet packet = createTestPacket(100);

-        assertEquals( 100, packet.capacity() );        

-        assertEquals( 0, packet.position());        

-        assertEquals( 100, packet.limit() );        

-        assertEquals( 100, packet.remaining() );        

-        assertTrue( packet.hasRemaining() );        

-    }

-    

-    public void testPosition() {

-        Packet packet = createTestPacket(100);

-        packet.position(10);

-        assertEquals( 10, packet.position() );        

-    }

-

-    public void testLimit() {

-        Packet packet = createTestPacket(100);

-        packet.limit(10);

-        assertEquals( 10, packet.limit() );        

-    }

-

-    public void testRemaining() {

-        Packet packet = createTestPacket(100);

-        packet.position(5);

-        packet.limit(95);

-        assertEquals(90, packet.remaining());

-        assertTrue(packet.hasRemaining());

-

-        packet.position(5);

-        packet.limit(5);

-        assertEquals(0, packet.remaining());

-        assertFalse(packet.hasRemaining());

-    }

-    

-    public void testFlip() {

-        Packet packet = createTestPacket(100);

-        packet.position(95);

-        packet.flip();        

-        assertEquals(0, packet.position());

-        assertEquals(95, packet.limit());

-    }

-    

-    public void testClear() {

-        Packet packet = createTestPacket(100);

-        packet.position(5);

-        packet.limit(95);

-        packet.clear();        

-        assertEquals(0, packet.position());

-        assertEquals(100, packet.limit());

-    }

-

-    public void testDuplicate() {

-        Packet packet = createTestPacket(100);

-        packet.position(5);

-        packet.limit(95);

-        Packet packet2 = packet.duplicate();

-        packet2.position(10);

-        packet2.limit(20);

-        

-        assertEquals(5, packet.position());

-        assertEquals(95, packet.limit());

-        assertEquals(10, packet2.position());

-        assertEquals(20, packet2.limit());

-    }

-

-    public void testRewind() {

-        Packet packet = createTestPacket(100);

-        packet.position(5);

-        packet.limit(95);

-        packet.rewind();

-        

-        assertEquals(0, packet.position());

-        assertEquals(95, packet.limit());

-    }

-    

-    public void testSlice() {

-        Packet packet = createTestPacket(100);

-        packet.position(5);

-        packet.limit(95);

-        Packet packet2 = packet.slice();

-        

-        assertEquals(0, packet2.position());

-        assertEquals(90, packet2.capacity());

-        assertEquals(90, packet2.limit());

-    }

-

-    public void testWriteAndReadByte() {

-        

-        Packet packet = createTestPacket(256);

-        for(int i=0; i < 256; i++) {

-            assertTrue(packet.write(i));

-        }

-        assertFalse(packet.write(0));

-        

-        packet.flip();

-        for(int i=0; i < 256; i++) {

-            assertEquals(i, packet.read());

-        }       

-        assertEquals(-1, packet.read());        

-    }

-    

-    public void testWriteAndReadBulkByte() {

-        

-        byte data[] = new byte[10];        

-        Packet packet = createTestPacket(data.length*10);

-        for(int i=0; i < 10; i++) {

-            Arrays.fill(data,(byte)i);

-            assertEquals(data.length, packet.write(data,0,data.length));

-        }

-        assertEquals(-1, packet.write(data,0,data.length));

-        

-        byte buffer[] = new byte[data.length];

-        packet.flip();

-        for(int i=0; i < 10; i++) {

-            assertEquals(buffer.length, packet.read(buffer,0,buffer.length));

-            Arrays.fill(data,(byte)i);

-            assertEquals(buffer, data);

-        }       

-        assertEquals(-1, packet.read(buffer,0,buffer.length));

-    }

- 

-    public void assertEquals(byte buffer[], byte data[]) {

-        assertEquals(buffer.length, data.length);

-        for (int i = 0; i < data.length; i++) {

-            assertEquals(buffer[i], data[i]);

-        }

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet;
+
+import java.util.Arrays;
+
+import org.apache.activeio.packet.Packet;
+
+import junit.framework.TestCase;
+
+
+/**
+ */
+abstract public class PacketTestSupport extends TestCase {
+    abstract Packet createTestPacket(int capacity);
+    
+    public void testInit() {
+        Packet packet = createTestPacket(100);
+        assertEquals( 100, packet.capacity() );        
+        assertEquals( 0, packet.position());        
+        assertEquals( 100, packet.limit() );        
+        assertEquals( 100, packet.remaining() );        
+        assertTrue( packet.hasRemaining() );        
+    }
+    
+    public void testPosition() {
+        Packet packet = createTestPacket(100);
+        packet.position(10);
+        assertEquals( 10, packet.position() );        
+    }
+
+    public void testLimit() {
+        Packet packet = createTestPacket(100);
+        packet.limit(10);
+        assertEquals( 10, packet.limit() );        
+    }
+
+    public void testRemaining() {
+        Packet packet = createTestPacket(100);
+        packet.position(5);
+        packet.limit(95);
+        assertEquals(90, packet.remaining());
+        assertTrue(packet.hasRemaining());
+
+        packet.position(5);
+        packet.limit(5);
+        assertEquals(0, packet.remaining());
+        assertFalse(packet.hasRemaining());
+    }
+    
+    public void testFlip() {
+        Packet packet = createTestPacket(100);
+        packet.position(95);
+        packet.flip();        
+        assertEquals(0, packet.position());
+        assertEquals(95, packet.limit());
+    }
+    
+    public void testClear() {
+        Packet packet = createTestPacket(100);
+        packet.position(5);
+        packet.limit(95);
+        packet.clear();        
+        assertEquals(0, packet.position());
+        assertEquals(100, packet.limit());
+    }
+
+    public void testDuplicate() {
+        Packet packet = createTestPacket(100);
+        packet.position(5);
+        packet.limit(95);
+        Packet packet2 = packet.duplicate();
+        packet2.position(10);
+        packet2.limit(20);
+        
+        assertEquals(5, packet.position());
+        assertEquals(95, packet.limit());
+        assertEquals(10, packet2.position());
+        assertEquals(20, packet2.limit());
+    }
+
+    public void testRewind() {
+        Packet packet = createTestPacket(100);
+        packet.position(5);
+        packet.limit(95);
+        packet.rewind();
+        
+        assertEquals(0, packet.position());
+        assertEquals(95, packet.limit());
+    }
+    
+    public void testSlice() {
+        Packet packet = createTestPacket(100);
+        packet.position(5);
+        packet.limit(95);
+        Packet packet2 = packet.slice();
+        
+        assertEquals(0, packet2.position());
+        assertEquals(90, packet2.capacity());
+        assertEquals(90, packet2.limit());
+    }
+
+    public void testWriteAndReadByte() {
+        
+        Packet packet = createTestPacket(256);
+        for(int i=0; i < 256; i++) {
+            assertTrue(packet.write(i));
+        }
+        assertFalse(packet.write(0));
+        
+        packet.flip();
+        for(int i=0; i < 256; i++) {
+            assertEquals(i, packet.read());
+        }       
+        assertEquals(-1, packet.read());        
+    }
+    
+    public void testWriteAndReadBulkByte() {
+        
+        byte data[] = new byte[10];        
+        Packet packet = createTestPacket(data.length*10);
+        for(int i=0; i < 10; i++) {
+            Arrays.fill(data,(byte)i);
+            assertEquals(data.length, packet.write(data,0,data.length));
+        }
+        assertEquals(-1, packet.write(data,0,data.length));
+        
+        byte buffer[] = new byte[data.length];
+        packet.flip();
+        for(int i=0; i < 10; i++) {
+            assertEquals(buffer.length, packet.read(buffer,0,buffer.length));
+            Arrays.fill(data,(byte)i);
+            assertEquals(buffer, data);
+        }       
+        assertEquals(-1, packet.read(buffer,0,buffer.length));
+    }
+ 
+    public void assertEquals(byte buffer[], byte data[]) {
+        assertEquals(buffer.length, data.length);
+        for (int i = 0; i < data.length; i++) {
+            assertEquals(buffer[i], data[i]);
+        }
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelTest.java
index 6eac40b..c116069 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/async/nio/NIOAsyncChannelTest.java
@@ -1,43 +1,43 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.nio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.async.nio.NIOAsyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-

-/**

- * @version $Revision$

- */

-public class NIOAsyncChannelTest extends SyncChannelTestSupport {

-

-    NIOAsyncChannelFactory factory = new NIOAsyncChannelFactory(true);

-    

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openAsyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindAsyncChannel(new URI("tcp://localhost:0"));

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.nio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.async.nio.NIOAsyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+
+/**
+ * @version $Revision$
+ */
+public class NIOAsyncChannelTest extends SyncChannelTestSupport {
+
+    NIOAsyncChannelFactory factory = new NIOAsyncChannelFactory(true);
+    
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openAsyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindAsyncChannel(new URI("tcp://localhost:0"));
+    }
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelTest.java
index 85d631f..72d8c9c 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeAsyncChannelTest.java
@@ -1,43 +1,43 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.vmpipe;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-

-/**

- * @version $Revision$

- */

-public class VMPipeAsyncChannelTest extends SyncChannelTestSupport {

-

-    VMPipeAsyncChannelFactory factory =  new VMPipeAsyncChannelFactory();

-

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openAsyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindAsyncChannel(new URI("vmpipe://testpipe"));

-    }

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.vmpipe;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+
+/**
+ * @version $Revision$
+ */
+public class VMPipeAsyncChannelTest extends SyncChannelTestSupport {
+
+    VMPipeAsyncChannelFactory factory =  new VMPipeAsyncChannelFactory();
+
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openAsyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindAsyncChannel(new URI("vmpipe://testpipe"));
+    }
+    
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeReflectionAsyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeReflectionAsyncChannelTest.java
index 5ab12f3..7bfed8f 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeReflectionAsyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/async/vmpipe/VMPipeReflectionAsyncChannelTest.java
@@ -1,45 +1,45 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.async.vmpipe;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-

-/**

- * @version $Revision$

- */

-public class VMPipeReflectionAsyncChannelTest extends SyncChannelTestSupport {

-

-    VMPipeAsyncChannelFactory factory =  new VMPipeAsyncChannelFactory();

-

-    protected Channel openChannel(URI connectURI) throws IOException {

-        factory.setForceRefelection(true);

-        return factory.openAsyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        factory.setForceRefelection(true);

-        return factory.bindAsyncChannel(new URI("vmpipe://testpipe"));

-    }

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.async.vmpipe;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.async.vmpipe.VMPipeAsyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+
+/**
+ * @version $Revision$
+ */
+public class VMPipeReflectionAsyncChannelTest extends SyncChannelTestSupport {
+
+    VMPipeAsyncChannelFactory factory =  new VMPipeAsyncChannelFactory();
+
+    protected Channel openChannel(URI connectURI) throws IOException {
+        factory.setForceRefelection(true);
+        return factory.openAsyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        factory.setForceRefelection(true);
+        return factory.bindAsyncChannel(new URI("vmpipe://testpipe"));
+    }
+    
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/nio/NIOSyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/nio/NIOSyncChannelTest.java
index 43b7271..efe5816 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/nio/NIOSyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/nio/NIOSyncChannelTest.java
@@ -1,44 +1,44 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.nio;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-import org.apache.activeio.packet.sync.nio.NIOSyncChannelFactory;

-

-/**

- * @version $Revision$

- */

-public class NIOSyncChannelTest extends SyncChannelTestSupport {

-

-    NIOSyncChannelFactory factory = new NIOSyncChannelFactory(true);

-    

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindSyncChannel(new URI("tcp://localhost:0"));

-    }

-    

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.nio;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+import org.apache.activeio.packet.sync.nio.NIOSyncChannelFactory;
+
+/**
+ * @version $Revision$
+ */
+public class NIOSyncChannelTest extends SyncChannelTestSupport {
+
+    NIOSyncChannelFactory factory = new NIOSyncChannelFactory(true);
+    
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindSyncChannel(new URI("tcp://localhost:0"));
+    }
+    
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/ConnectionlessSyncChannelTestSupport.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/ConnectionlessSyncChannelTestSupport.java
index 10e93bb..7393547 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/ConnectionlessSyncChannelTestSupport.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/ConnectionlessSyncChannelTestSupport.java
@@ -1,182 +1,182 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync;

-

-import edu.emory.mathcs.backport.java.util.concurrent.Executor;

-import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.adapter.AsyncToSyncChannel;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.FilterPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.datagram.DatagramContext;

-import org.apache.commons.logging.Log;

-import org.apache.commons.logging.LogFactory;

-

-import java.io.IOException;

-import java.net.DatagramPacket;

-import java.net.InetSocketAddress;

-import java.net.SocketAddress;

-import java.net.SocketException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import junit.framework.TestCase;

-

-

-/**

- * @version $Revision$

- */

-abstract public class ConnectionlessSyncChannelTestSupport extends TestCase {

-

-    private final Log log = LogFactory.getLog(ConnectionlessSyncChannelTestSupport.class);

-    private SyncChannel clientChannel;

-    private SyncChannel serverChannel;

-    private final Executor sendExecutor = new ScheduledThreadPoolExecutor(1);

-

-    public void testSmallSendReceive() throws IOException, URISyntaxException, InterruptedException {

-        if (isDisabled()) {

-            log.info("test disabled: " + getName());

-            return;

-        }

-        UDPFilterPacket fp = new UDPFilterPacket("Hello World".getBytes(), new InetSocketAddress(getAddress(), 4444));

-        doSendReceive(fp.duplicate());

-    }

-

-    public void testManySmallSendReceives() throws IOException, URISyntaxException, InterruptedException {

-        if (isDisabled()) {

-            log.info("test disabled: " + getName());

-            return;

-        }

-        log.info("Start of testManySmallSendReceives");

-        UDPFilterPacket fp = new UDPFilterPacket("Hello World".getBytes(), new InetSocketAddress(getAddress(), 4444));

-        long start = System.currentTimeMillis();

-        for (int i = 0; i < getTestIterations(); i++) {

-            doSendReceive(fp.duplicate());

-        }

-        long end = System.currentTimeMillis();

-        log.info("done. Duration: " + duration(start, end) + "s, duration per send: " + (unitDuration(start, end, getTestIterations()) * 1000.0) + "ms");

-    }

-

-    private float unitDuration(long start, long end, int testIterations) {

-        return duration(start, end) / testIterations;

-    }

-

-    private float duration(long start, long end) {

-        return (float) (((float) (end - start)) / 1000.0f);

-    }

-

-    protected int getTestIterations() {

-        return 1000;

-    }

-

-    protected void setUp() throws Exception {

-

-        log.info("Running: " + getName());

-

-        if (isDisabled()) {

-            return;

-        }

-

-        log.info("Client connecting to: " + getAddress() + ":4444");

-

-        clientChannel = AsyncToSyncChannel.adapt(openClientChannel(new URI("test://" + getAddress() + ":4444")));

-        clientChannel.start();

-

-        serverChannel = AsyncToSyncChannel.adapt(openServerChannel(new URI("test://" + getAddress() + ":4444")));

-        serverChannel.start();

-    }

-

-    private void doSendReceive(final Packet outboundPacket) throws IOException, InterruptedException {

-        ByteArrayPacket ip = new ByteArrayPacket(new byte[outboundPacket.remaining()]);

-

-        // Do the send async.

-        sendExecutor.execute(new Runnable() {

-            public void run() {

-                try {

-                    clientChannel.write(outboundPacket);

-                    clientChannel.flush();

-                }

-                catch (Exception e) {

-                    int i = 0;

-                }

-            }

-        });

-

-        while (ip.hasRemaining()) {

-            Packet packet = serverChannel.read(1000 * 5);

-            assertNotNull(packet);

-            packet.read(ip);

-        }

-        outboundPacket.clear();

-        ip.clear();

-        assertEquals(outboundPacket.sliceAsBytes(), ip.sliceAsBytes());

-    }

-

-    protected void tearDown() throws Exception {

-        if (isDisabled()) return;

-

-        log.info("Closing down the channels.");

-

-        serverChannel.dispose();

-        clientChannel.dispose();

-    }

-

-    protected boolean isDisabled() {

-        return false;

-    }

-

-    public void assertEquals(byte []b1, byte[] b2) {

-        assertEquals(b1.length, b2.length);

-        for (int i = 0; i < b2.length; i++) {

-            assertEquals(b1[i], b2[i]);

-        }

-    }

-

-    abstract protected Channel openClientChannel(URI connectURI) throws IOException;

-

-    abstract protected Channel openServerChannel(URI connectURI) throws IOException;

-

-    abstract protected String getAddress();

-

-    private final class UDPFilterPacket extends FilterPacket {

-        private final DatagramPacket packet;

-

-        private UDPFilterPacket(byte[] buf, SocketAddress address) throws SocketException {

-            super(new ByteArrayPacket(buf));

-            this.packet = new DatagramPacket(buf, buf.length, address);

-        }

-

-        private UDPFilterPacket(Packet op, DatagramPacket packet) {

-            super(op);

-            this.packet = packet;

-        }

-

-        public Object getAdapter(Class target) {

-            if (target == DatagramContext.class) {

-                return new DatagramContext(packet);

-            }

-            return super.getAdapter(target);

-        }

-

-        public Packet filter(Packet packet) {

-            return new UDPFilterPacket(packet, this.packet);

-        }

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync;
+
+import edu.emory.mathcs.backport.java.util.concurrent.Executor;
+import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.adapter.AsyncToSyncChannel;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.FilterPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.datagram.DatagramContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import junit.framework.TestCase;
+
+
+/**
+ * @version $Revision$
+ */
+abstract public class ConnectionlessSyncChannelTestSupport extends TestCase {
+
+    private final Log log = LogFactory.getLog(ConnectionlessSyncChannelTestSupport.class);
+    private SyncChannel clientChannel;
+    private SyncChannel serverChannel;
+    private final Executor sendExecutor = new ScheduledThreadPoolExecutor(1);
+
+    public void testSmallSendReceive() throws IOException, URISyntaxException, InterruptedException {
+        if (isDisabled()) {
+            log.info("test disabled: " + getName());
+            return;
+        }
+        UDPFilterPacket fp = new UDPFilterPacket("Hello World".getBytes(), new InetSocketAddress(getAddress(), 4444));
+        doSendReceive(fp.duplicate());
+    }
+
+    public void testManySmallSendReceives() throws IOException, URISyntaxException, InterruptedException {
+        if (isDisabled()) {
+            log.info("test disabled: " + getName());
+            return;
+        }
+        log.info("Start of testManySmallSendReceives");
+        UDPFilterPacket fp = new UDPFilterPacket("Hello World".getBytes(), new InetSocketAddress(getAddress(), 4444));
+        long start = System.currentTimeMillis();
+        for (int i = 0; i < getTestIterations(); i++) {
+            doSendReceive(fp.duplicate());
+        }
+        long end = System.currentTimeMillis();
+        log.info("done. Duration: " + duration(start, end) + "s, duration per send: " + (unitDuration(start, end, getTestIterations()) * 1000.0) + "ms");
+    }
+
+    private float unitDuration(long start, long end, int testIterations) {
+        return duration(start, end) / testIterations;
+    }
+
+    private float duration(long start, long end) {
+        return (float) (((float) (end - start)) / 1000.0f);
+    }
+
+    protected int getTestIterations() {
+        return 1000;
+    }
+
+    protected void setUp() throws Exception {
+
+        log.info("Running: " + getName());
+
+        if (isDisabled()) {
+            return;
+        }
+
+        log.info("Client connecting to: " + getAddress() + ":4444");
+
+        clientChannel = AsyncToSyncChannel.adapt(openClientChannel(new URI("test://" + getAddress() + ":4444")));
+        clientChannel.start();
+
+        serverChannel = AsyncToSyncChannel.adapt(openServerChannel(new URI("test://" + getAddress() + ":4444")));
+        serverChannel.start();
+    }
+
+    private void doSendReceive(final Packet outboundPacket) throws IOException, InterruptedException {
+        ByteArrayPacket ip = new ByteArrayPacket(new byte[outboundPacket.remaining()]);
+
+        // Do the send async.
+        sendExecutor.execute(new Runnable() {
+            public void run() {
+                try {
+                    clientChannel.write(outboundPacket);
+                    clientChannel.flush();
+                }
+                catch (Exception e) {
+                    int i = 0;
+                }
+            }
+        });
+
+        while (ip.hasRemaining()) {
+            Packet packet = serverChannel.read(1000 * 5);
+            assertNotNull(packet);
+            packet.read(ip);
+        }
+        outboundPacket.clear();
+        ip.clear();
+        assertEquals(outboundPacket.sliceAsBytes(), ip.sliceAsBytes());
+    }
+
+    protected void tearDown() throws Exception {
+        if (isDisabled()) return;
+
+        log.info("Closing down the channels.");
+
+        serverChannel.dispose();
+        clientChannel.dispose();
+    }
+
+    protected boolean isDisabled() {
+        return false;
+    }
+
+    public void assertEquals(byte []b1, byte[] b2) {
+        assertEquals(b1.length, b2.length);
+        for (int i = 0; i < b2.length; i++) {
+            assertEquals(b1[i], b2[i]);
+        }
+    }
+
+    abstract protected Channel openClientChannel(URI connectURI) throws IOException;
+
+    abstract protected Channel openServerChannel(URI connectURI) throws IOException;
+
+    abstract protected String getAddress();
+
+    private final class UDPFilterPacket extends FilterPacket {
+        private final DatagramPacket packet;
+
+        private UDPFilterPacket(byte[] buf, SocketAddress address) throws SocketException {
+            super(new ByteArrayPacket(buf));
+            this.packet = new DatagramPacket(buf, buf.length, address);
+        }
+
+        private UDPFilterPacket(Packet op, DatagramPacket packet) {
+            super(op);
+            this.packet = packet;
+        }
+
+        public Object getAdapter(Class target) {
+            if (target == DatagramContext.class) {
+                return new DatagramContext(packet);
+            }
+            return super.getAdapter(target);
+        }
+
+        public Packet filter(Packet packet) {
+            return new UDPFilterPacket(packet, this.packet);
+        }
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/SlowWriteSyncChannelFactory.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/SlowWriteSyncChannelFactory.java
index 60a6580..803ec59 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/SlowWriteSyncChannelFactory.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/SlowWriteSyncChannelFactory.java
@@ -1,93 +1,93 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync;

-

-import java.io.IOException;

-import java.io.InterruptedIOException;

-import java.net.URI;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.FilterSyncChannel;

-import org.apache.activeio.packet.sync.FilterSyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-

-/**

- * Makes all the channels produced by another [@see org.apache.activeio.SyncChannelFactory}

- * have write operations that have built in delays for testing. 

- * 

- * @version $Revision$

- */

-public class SlowWriteSyncChannelFactory implements SyncChannelFactory {

-    

-    final SyncChannelFactory next;

-    private final int maxPacketSize;

-    private final long packetDelay;

-

-    public SlowWriteSyncChannelFactory(final SyncChannelFactory next, int maxPacketSize, long packetDelay) {

-        this.next = next;

-        this.maxPacketSize = maxPacketSize;

-        this.packetDelay = packetDelay;

-    }

-    

-    class SlowWriteSyncChannel extends FilterSyncChannel {

-        public SlowWriteSyncChannel(SyncChannel next) {

-            super(next);

-        }

-        public void write(Packet packet) throws IOException {

-            packet = packet.slice();

-            while(packet.hasRemaining()) {

-                int size = Math.max(maxPacketSize, packet.remaining());

-                packet.position(size);

-                Packet remaining = packet.slice();

-                packet.flip();

-                Packet data = packet.slice();

-                super.write(data);

-                packet = remaining;

-                try {

-                    Thread.sleep(packetDelay);

-                } catch (InterruptedException e) {

-                    throw new InterruptedIOException();

-                }

-            }

-        }

-    }

-

-    class SlowWriteSyncChannelServer extends FilterSyncChannelServer {

-        public SlowWriteSyncChannelServer(SyncChannelServer next) {

-            super(next);

-        }

-        public Channel accept(long timeout) throws IOException {

-            Channel channel = super.accept(timeout);

-            if( channel != null ) {

-                channel =  new SlowWriteSyncChannel((SyncChannel) channel);

-            }

-            return channel;

-        }

-    }

-    

-    public SyncChannelServer bindSyncChannel(URI location) throws IOException {

-        return next.bindSyncChannel(location);

-    }

-    

-    public SyncChannel openSyncChannel(URI location) throws IOException {

-        return new SlowWriteSyncChannel(next.openSyncChannel(location));

-    }

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.URI;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.FilterSyncChannel;
+import org.apache.activeio.packet.sync.FilterSyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+
+/**
+ * Makes all the channels produced by another [@see org.apache.activeio.SyncChannelFactory}
+ * have write operations that have built in delays for testing. 
+ * 
+ * @version $Revision$
+ */
+public class SlowWriteSyncChannelFactory implements SyncChannelFactory {
+    
+    final SyncChannelFactory next;
+    private final int maxPacketSize;
+    private final long packetDelay;
+
+    public SlowWriteSyncChannelFactory(final SyncChannelFactory next, int maxPacketSize, long packetDelay) {
+        this.next = next;
+        this.maxPacketSize = maxPacketSize;
+        this.packetDelay = packetDelay;
+    }
+    
+    class SlowWriteSyncChannel extends FilterSyncChannel {
+        public SlowWriteSyncChannel(SyncChannel next) {
+            super(next);
+        }
+        public void write(Packet packet) throws IOException {
+            packet = packet.slice();
+            while(packet.hasRemaining()) {
+                int size = Math.max(maxPacketSize, packet.remaining());
+                packet.position(size);
+                Packet remaining = packet.slice();
+                packet.flip();
+                Packet data = packet.slice();
+                super.write(data);
+                packet = remaining;
+                try {
+                    Thread.sleep(packetDelay);
+                } catch (InterruptedException e) {
+                    throw new InterruptedIOException();
+                }
+            }
+        }
+    }
+
+    class SlowWriteSyncChannelServer extends FilterSyncChannelServer {
+        public SlowWriteSyncChannelServer(SyncChannelServer next) {
+            super(next);
+        }
+        public Channel accept(long timeout) throws IOException {
+            Channel channel = super.accept(timeout);
+            if( channel != null ) {
+                channel =  new SlowWriteSyncChannel((SyncChannel) channel);
+            }
+            return channel;
+        }
+    }
+    
+    public SyncChannelServer bindSyncChannel(URI location) throws IOException {
+        return next.bindSyncChannel(location);
+    }
+    
+    public SyncChannel openSyncChannel(URI location) throws IOException {
+        return new SlowWriteSyncChannel(next.openSyncChannel(location));
+    }
+    
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/SyncChannelTestSupport.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/SyncChannelTestSupport.java
index d942b81..b844f3b 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/SyncChannelTestSupport.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/SyncChannelTestSupport.java
@@ -1,201 +1,201 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync;

-

-import edu.emory.mathcs.backport.java.util.concurrent.Executor;

-import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;

-import edu.emory.mathcs.backport.java.util.concurrent.Semaphore;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.adapter.AsyncToSyncChannel;

-import org.apache.activeio.adapter.AsyncToSyncChannelServer;

-import org.apache.activeio.packet.ByteArrayPacket;

-import org.apache.activeio.packet.EOSPacket;

-import org.apache.activeio.packet.Packet;

-import org.apache.activeio.packet.sync.SyncChannel;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.apache.activeio.stream.sync.socket.SocketMetadata;

-import org.apache.commons.logging.Log;

-import org.apache.commons.logging.LogFactory;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import junit.framework.TestCase;

-

-

-/**

- * Used to test the {@see org.apache.activeio.net.TcpSynchChannel}

- *  

- * @version $Revision$

- */

-abstract public class SyncChannelTestSupport extends TestCase {

-

-    Log log = LogFactory.getLog(SyncChannelTestSupport.class);

-    private SyncChannelServer server;

-    private SyncChannel clientChannel;

-    private SyncChannel serverChannel;

-    Executor sendExecutor = new ScheduledThreadPoolExecutor(1);

-

-    public void testSmallSendReceive() throws IOException, URISyntaxException, InterruptedException {

-        if( isDisabled() ) {

-            log.info("test disabled: "+getName());

-            return;

-        }

-        Packet outboundPacket = new ByteArrayPacket("Hello World".getBytes());

-        doSendReceive(outboundPacket.duplicate());

-    }

-

-    public void testPeerDisconnect() throws IOException, URISyntaxException, InterruptedException {

-        if( isDisabled() ) {

-            log.info("test disabled: "+getName());

-            return;

-        }

-

-        Packet outboundPacket = new ByteArrayPacket("Hello World".getBytes());

-        doSendReceive(outboundPacket.duplicate());

-        // disconnect the client.

-        clientChannel.dispose();

-

-        // The server should get an EOS packet.

-        Packet packet = serverChannel.read(1000);

-        assertEquals(EOSPacket.EOS_PACKET, packet);

-    }

-

-    public void testManySmallSendReceives() throws IOException, URISyntaxException, InterruptedException {

-        if( isDisabled() ) {

-            log.info("test disabled: "+getName());

-            return;

-        }

-        log.info("Start of testManySmallSendReceives");

-        Packet outboundPacket = new ByteArrayPacket("Hello World".getBytes());

-        long start = System.currentTimeMillis();

-        for( int i=0; i < getTestIterations(); i++ ) {

-            doSendReceive(outboundPacket.duplicate());

-        }

-        long end = System.currentTimeMillis();

-        log.info("done. Duration: "+duration(start,end)+", duration per send: "+unitDuration(start, end, getTestIterations()));

-    }

-

-    private float unitDuration(long start, long end, int testIterations) {

-                return duration(start,end)/testIterations;

-        }

-

-        private float duration(long start, long end) {

-                return (float) (((float)(end-start))/1000.0f);

-        }

-

-        protected int getTestIterations() {

-        return 1000;

-    }

-

-    protected void setUp() throws Exception {

-

-        log.info("Running: "+getName());

-

-        if( isDisabled() ) {

-            return;

-        }

-

-        log.info("Bind to an annonymous tcp port.");

-        server = AsyncToSyncChannelServer.adapt(bindChannel());

-        server.start();

-        log.info("Server Bound at URI: "+server.getBindURI());

-

-        log.info("Client connecting to: "+server.getConnectURI());

-        clientChannel = AsyncToSyncChannel.adapt( openChannel(server.getConnectURI()));

-        clientChannel.start();

-        SocketMetadata socket = (SocketMetadata) clientChannel.getAdapter(SocketMetadata.class);

-        if( socket != null )

-            socket.setTcpNoDelay(true);

-        log.info("Get connection that was accepted on the server side.");

-

-        Channel c = server.accept(1000*5);

-        assertNotNull(c);

-

-        serverChannel = AsyncToSyncChannel.adapt(c);

-        serverChannel.start();

-        socket = (SocketMetadata) serverChannel.getAdapter(SocketMetadata.class);

-        if( socket != null ) {

-            socket.setTcpNoDelay(true);

-            log.info("Server Channel's Remote addreess: "+socket.getRemoteSocketAddress());

-            log.info("Server Channel's Local addreess: "+socket.getLocalSocketAddress());

-        }

-    }

-

-    /**

-     * @param outboundPacket

-     * @throws IOException

-     * @throws URISyntaxException

-     * @throws InterruptedException

-     */

-    private void doSendReceive(final Packet outboundPacket) throws IOException, URISyntaxException, InterruptedException {

-        ByteArrayPacket inboundPacket = new ByteArrayPacket(new byte[outboundPacket.remaining()]);

-        final Semaphore runMutext = new Semaphore(0);

-

-        // Do the send async.

-        sendExecutor.execute( new Runnable() {

-            public void run() {

-                try {

-                    clientChannel.write(outboundPacket);

-                    clientChannel.flush();

-                    runMutext.release();

-                } catch (IOException e) {

-                }

-            }

-        });

-

-        while( inboundPacket.hasRemaining() ) {

-            Packet packet = serverChannel.read(1000*5);

-            assertNotNull(packet);

-            packet.read(inboundPacket);

-        }

-        outboundPacket.clear();

-        inboundPacket.clear();

-        assertEquals(outboundPacket.sliceAsBytes(), inboundPacket.sliceAsBytes());

-

-        runMutext.acquire();

-    }

-

-    protected void tearDown() throws Exception {

-        if( isDisabled() ) {

-            return;

-        }

-        log.info("Closing down the channels.");

-        serverChannel.dispose();

-        clientChannel.dispose();

-        server.dispose();

-    }

-

-    protected boolean isDisabled() {

-        return false;

-    }

-

-    public void assertEquals(byte []b1, byte[] b2 ) {

-        assertEquals(b1.length, b2.length);

-        for (int i = 0; i < b2.length; i++) {

-            assertEquals(b1[i], b2[i]);

-        }

-    }

-

-    abstract protected Channel openChannel(URI connectURI) throws IOException ;

-    abstract protected ChannelServer bindChannel() throws IOException, URISyntaxException;

-

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync;
+
+import edu.emory.mathcs.backport.java.util.concurrent.Executor;
+import edu.emory.mathcs.backport.java.util.concurrent.ScheduledThreadPoolExecutor;
+import edu.emory.mathcs.backport.java.util.concurrent.Semaphore;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.adapter.AsyncToSyncChannel;
+import org.apache.activeio.adapter.AsyncToSyncChannelServer;
+import org.apache.activeio.packet.ByteArrayPacket;
+import org.apache.activeio.packet.EOSPacket;
+import org.apache.activeio.packet.Packet;
+import org.apache.activeio.packet.sync.SyncChannel;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.apache.activeio.stream.sync.socket.SocketMetadata;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import junit.framework.TestCase;
+
+
+/**
+ * Used to test the {@see org.apache.activeio.net.TcpSynchChannel}
+ *  
+ * @version $Revision$
+ */
+abstract public class SyncChannelTestSupport extends TestCase {
+
+    Log log = LogFactory.getLog(SyncChannelTestSupport.class);
+    private SyncChannelServer server;
+    private SyncChannel clientChannel;
+    private SyncChannel serverChannel;
+    Executor sendExecutor = new ScheduledThreadPoolExecutor(1);
+
+    public void testSmallSendReceive() throws IOException, URISyntaxException, InterruptedException {
+        if( isDisabled() ) {
+            log.info("test disabled: "+getName());
+            return;
+        }
+        Packet outboundPacket = new ByteArrayPacket("Hello World".getBytes());
+        doSendReceive(outboundPacket.duplicate());
+    }
+
+    public void testPeerDisconnect() throws IOException, URISyntaxException, InterruptedException {
+        if( isDisabled() ) {
+            log.info("test disabled: "+getName());
+            return;
+        }
+
+        Packet outboundPacket = new ByteArrayPacket("Hello World".getBytes());
+        doSendReceive(outboundPacket.duplicate());
+        // disconnect the client.
+        clientChannel.dispose();
+
+        // The server should get an EOS packet.
+        Packet packet = serverChannel.read(1000);
+        assertEquals(EOSPacket.EOS_PACKET, packet);
+    }
+
+    public void testManySmallSendReceives() throws IOException, URISyntaxException, InterruptedException {
+        if( isDisabled() ) {
+            log.info("test disabled: "+getName());
+            return;
+        }
+        log.info("Start of testManySmallSendReceives");
+        Packet outboundPacket = new ByteArrayPacket("Hello World".getBytes());
+        long start = System.currentTimeMillis();
+        for( int i=0; i < getTestIterations(); i++ ) {
+            doSendReceive(outboundPacket.duplicate());
+        }
+        long end = System.currentTimeMillis();
+        log.info("done. Duration: "+duration(start,end)+", duration per send: "+unitDuration(start, end, getTestIterations()));
+    }
+
+    private float unitDuration(long start, long end, int testIterations) {
+                return duration(start,end)/testIterations;
+        }
+
+        private float duration(long start, long end) {
+                return (float) (((float)(end-start))/1000.0f);
+        }
+
+        protected int getTestIterations() {
+        return 1000;
+    }
+
+    protected void setUp() throws Exception {
+
+        log.info("Running: "+getName());
+
+        if( isDisabled() ) {
+            return;
+        }
+
+        log.info("Bind to an annonymous tcp port.");
+        server = AsyncToSyncChannelServer.adapt(bindChannel());
+        server.start();
+        log.info("Server Bound at URI: "+server.getBindURI());
+
+        log.info("Client connecting to: "+server.getConnectURI());
+        clientChannel = AsyncToSyncChannel.adapt( openChannel(server.getConnectURI()));
+        clientChannel.start();
+        SocketMetadata socket = (SocketMetadata) clientChannel.getAdapter(SocketMetadata.class);
+        if( socket != null )
+            socket.setTcpNoDelay(true);
+        log.info("Get connection that was accepted on the server side.");
+
+        Channel c = server.accept(1000*5);
+        assertNotNull(c);
+
+        serverChannel = AsyncToSyncChannel.adapt(c);
+        serverChannel.start();
+        socket = (SocketMetadata) serverChannel.getAdapter(SocketMetadata.class);
+        if( socket != null ) {
+            socket.setTcpNoDelay(true);
+            log.info("Server Channel's Remote addreess: "+socket.getRemoteSocketAddress());
+            log.info("Server Channel's Local addreess: "+socket.getLocalSocketAddress());
+        }
+    }
+
+    /**
+     * @param outboundPacket
+     * @throws IOException
+     * @throws URISyntaxException
+     * @throws InterruptedException
+     */
+    private void doSendReceive(final Packet outboundPacket) throws IOException, URISyntaxException, InterruptedException {
+        ByteArrayPacket inboundPacket = new ByteArrayPacket(new byte[outboundPacket.remaining()]);
+        final Semaphore runMutext = new Semaphore(0);
+
+        // Do the send async.
+        sendExecutor.execute( new Runnable() {
+            public void run() {
+                try {
+                    clientChannel.write(outboundPacket);
+                    clientChannel.flush();
+                    runMutext.release();
+                } catch (IOException e) {
+                }
+            }
+        });
+
+        while( inboundPacket.hasRemaining() ) {
+            Packet packet = serverChannel.read(1000*5);
+            assertNotNull(packet);
+            packet.read(inboundPacket);
+        }
+        outboundPacket.clear();
+        inboundPacket.clear();
+        assertEquals(outboundPacket.sliceAsBytes(), inboundPacket.sliceAsBytes());
+
+        runMutext.acquire();
+    }
+
+    protected void tearDown() throws Exception {
+        if( isDisabled() ) {
+            return;
+        }
+        log.info("Closing down the channels.");
+        serverChannel.dispose();
+        clientChannel.dispose();
+        server.dispose();
+    }
+
+    protected boolean isDisabled() {
+        return false;
+    }
+
+    public void assertEquals(byte []b1, byte[] b2 ) {
+        assertEquals(b1.length, b2.length);
+        for (int i = 0; i < b2.length; i++) {
+            assertEquals(b1[i], b2[i]);
+        }
+    }
+
+    abstract protected Channel openChannel(URI connectURI) throws IOException ;
+    abstract protected ChannelServer bindChannel() throws IOException, URISyntaxException;
+
+
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/datagram/DatagramSyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/datagram/DatagramSyncChannelTest.java
index 2671f25..8c0b0b2 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/datagram/DatagramSyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/datagram/DatagramSyncChannelTest.java
@@ -1,45 +1,45 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.datagram;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.sync.ConnectionlessSyncChannelTestSupport;

-import org.apache.activeio.packet.sync.datagram.DatagramSocketSyncChannelFactory;

-

-

-/**

- * @version $Revision$

- */

-public class DatagramSyncChannelTest extends ConnectionlessSyncChannelTestSupport {

-

-    DatagramSocketSyncChannelFactory factory = new DatagramSocketSyncChannelFactory();

-

-    protected Channel openClientChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(null);

-    }

-

-    protected Channel openServerChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(null, connectURI);

-    }

-

-    protected String getAddress() {

-        return "127.0.0.1";

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.datagram;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.sync.ConnectionlessSyncChannelTestSupport;
+import org.apache.activeio.packet.sync.datagram.DatagramSocketSyncChannelFactory;
+
+
+/**
+ * @version $Revision$
+ */
+public class DatagramSyncChannelTest extends ConnectionlessSyncChannelTestSupport {
+
+    DatagramSocketSyncChannelFactory factory = new DatagramSocketSyncChannelFactory();
+
+    protected Channel openClientChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(null);
+    }
+
+    protected Channel openServerChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(null, connectURI);
+    }
+
+    protected String getAddress() {
+        return "127.0.0.1";
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/multicast/MulticastSyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/multicast/MulticastSyncChannelTest.java
index 5283011..2457494 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/multicast/MulticastSyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/multicast/MulticastSyncChannelTest.java
@@ -1,45 +1,45 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.multicast;

-

-import java.io.IOException;

-import java.net.URI;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.packet.sync.ConnectionlessSyncChannelTestSupport;

-import org.apache.activeio.packet.sync.multicast.MulticastSocketSyncChannelFactory;

-

-

-/**

- * @version $Revision$

- */

-public class MulticastSyncChannelTest extends ConnectionlessSyncChannelTestSupport {

-

-    MulticastSocketSyncChannelFactory factory = new MulticastSocketSyncChannelFactory();

-

-    protected Channel openClientChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(connectURI);

-    }

-

-    protected Channel openServerChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(connectURI, null);

-    }

-

-    protected String getAddress() {

-        return "224.2.2.2";

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.multicast;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.packet.sync.ConnectionlessSyncChannelTestSupport;
+import org.apache.activeio.packet.sync.multicast.MulticastSocketSyncChannelFactory;
+
+
+/**
+ * @version $Revision$
+ */
+public class MulticastSyncChannelTest extends ConnectionlessSyncChannelTestSupport {
+
+    MulticastSocketSyncChannelFactory factory = new MulticastSocketSyncChannelFactory();
+
+    protected Channel openClientChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(connectURI);
+    }
+
+    protected Channel openServerChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(connectURI, null);
+    }
+
+    protected String getAddress() {
+        return "224.2.2.2";
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketChannelSyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketChannelSyncChannelTest.java
index dd90ea7..1245971 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketChannelSyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketChannelSyncChannelTest.java
@@ -1,50 +1,50 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.socket;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.sync.SlowWriteSyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-import org.apache.activeio.packet.sync.nio.NIOSyncChannelFactory;

-

-/**

- * @version $Revision$

- */

-public class SlowSocketChannelSyncChannelTest extends SyncChannelTestSupport {

-

-    SlowWriteSyncChannelFactory factory = new SlowWriteSyncChannelFactory(new NIOSyncChannelFactory(true), 1, 100);

-

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindSyncChannel(new URI("tcp://localhost:0"));

-    }

-

-    /**

-     * Reduce the number if iterations since we are running slower than normal.

-     */

-    protected int getTestIterations() {

-        return 25;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.socket;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.sync.SlowWriteSyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+import org.apache.activeio.packet.sync.nio.NIOSyncChannelFactory;
+
+/**
+ * @version $Revision$
+ */
+public class SlowSocketChannelSyncChannelTest extends SyncChannelTestSupport {
+
+    SlowWriteSyncChannelFactory factory = new SlowWriteSyncChannelFactory(new NIOSyncChannelFactory(true), 1, 100);
+
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindSyncChannel(new URI("tcp://localhost:0"));
+    }
+
+    /**
+     * Reduce the number if iterations since we are running slower than normal.
+     */
+    protected int getTestIterations() {
+        return 25;
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketSyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketSyncChannelTest.java
index eb53e0b..604b5cf 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketSyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SlowSocketSyncChannelTest.java
@@ -1,50 +1,50 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.socket;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.sync.SlowWriteSyncChannelFactory;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;

-

-/**

- * @version $Revision$

- */

-public class SlowSocketSyncChannelTest extends SyncChannelTestSupport {

-

-    SlowWriteSyncChannelFactory factory = new SlowWriteSyncChannelFactory(new SocketSyncChannelFactory(), 4, 1);

-

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindSyncChannel(new URI("tcp://localhost:0"));

-    }

-

-    /**

-     * Reduce the number if iterations since we are running slower than normal.

-     */

-    protected int getTestIterations() {

-        return 25;

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.socket;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.sync.SlowWriteSyncChannelFactory;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;
+
+/**
+ * @version $Revision$
+ */
+public class SlowSocketSyncChannelTest extends SyncChannelTestSupport {
+
+    SlowWriteSyncChannelFactory factory = new SlowWriteSyncChannelFactory(new SocketSyncChannelFactory(), 4, 1);
+
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindSyncChannel(new URI("tcp://localhost:0"));
+    }
+
+    /**
+     * Reduce the number if iterations since we are running slower than normal.
+     */
+    protected int getTestIterations() {
+        return 25;
+    }
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelTest.java
index 6e2ea4b..0287026 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/socket/SocketSyncChannelTest.java
@@ -1,43 +1,43 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.socket;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;

-

-/**

- * @version $Revision$

- */

-public class SocketSyncChannelTest extends SyncChannelTestSupport {

-

-    SocketSyncChannelFactory factory = new SocketSyncChannelFactory();

-    

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindSyncChannel(new URI("tcp://localhost:0"));

-    }

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.socket;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;
+
+/**
+ * @version $Revision$
+ */
+public class SocketSyncChannelTest extends SyncChannelTestSupport {
+
+    SocketSyncChannelFactory factory = new SocketSyncChannelFactory();
+    
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindSyncChannel(new URI("tcp://localhost:0"));
+    }
+    
+}
diff --git a/activeio-core/src/test/java/org/apache/activeio/packet/sync/ssl/SslSocketSynchChannelTest.java b/activeio-core/src/test/java/org/apache/activeio/packet/sync/ssl/SslSocketSynchChannelTest.java
index 940bf7e..021601a 100644
--- a/activeio-core/src/test/java/org/apache/activeio/packet/sync/ssl/SslSocketSynchChannelTest.java
+++ b/activeio-core/src/test/java/org/apache/activeio/packet/sync/ssl/SslSocketSynchChannelTest.java
@@ -1,53 +1,53 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.ssl;

-

-import java.io.IOException;

-import java.net.URI;

-import java.net.URISyntaxException;

-

-import org.apache.activeio.Channel;

-import org.apache.activeio.ChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelTestSupport;

-import org.apache.activeio.packet.sync.ssl.SslSocketSyncChannelFactory;

-

-/**

- * @version $Revision$

- */

-public class SslSocketSynchChannelTest extends SyncChannelTestSupport {

-

-    static {

-        String basedir = System.getProperty("basedir");

-        System.setProperty("javax.net.ssl.trustStore", basedir+"/src/test/resources/client.keystore");

-        System.setProperty("javax.net.ssl.trustStorePassword", "password");

-        System.setProperty("javax.net.ssl.trustStoreType", "jks");        

-        System.setProperty("javax.net.ssl.keyStore", basedir+"/src/test/resources/server.keystore");

-        System.setProperty("javax.net.ssl.keyStorePassword", "password");

-        System.setProperty("javax.net.ssl.keyStoreType", "jks");        

-        //System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");        

-    }

-    

-    SslSocketSyncChannelFactory factory = new SslSocketSyncChannelFactory();

-    

-    protected Channel openChannel(URI connectURI) throws IOException {

-        return factory.openSyncChannel(connectURI);

-    }

-

-    protected ChannelServer bindChannel() throws IOException, URISyntaxException {

-        return factory.bindSyncChannel(new URI("ssl://localhost:0"));

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.ssl;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.activeio.Channel;
+import org.apache.activeio.ChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelTestSupport;
+import org.apache.activeio.packet.sync.ssl.SslSocketSyncChannelFactory;
+
+/**
+ * @version $Revision$
+ */
+public class SslSocketSynchChannelTest extends SyncChannelTestSupport {
+
+    static {
+        String basedir = System.getProperty("basedir");
+        System.setProperty("javax.net.ssl.trustStore", basedir+"/src/test/resources/client.keystore");
+        System.setProperty("javax.net.ssl.trustStorePassword", "password");
+        System.setProperty("javax.net.ssl.trustStoreType", "jks");        
+        System.setProperty("javax.net.ssl.keyStore", basedir+"/src/test/resources/server.keystore");
+        System.setProperty("javax.net.ssl.keyStorePassword", "password");
+        System.setProperty("javax.net.ssl.keyStoreType", "jks");        
+        //System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");        
+    }
+    
+    SslSocketSyncChannelFactory factory = new SslSocketSyncChannelFactory();
+    
+    protected Channel openChannel(URI connectURI) throws IOException {
+        return factory.openSyncChannel(connectURI);
+    }
+
+    protected ChannelServer bindChannel() throws IOException, URISyntaxException {
+        return factory.bindSyncChannel(new URI("ssl://localhost:0"));
+    }
+}
diff --git a/activeio-jxta/src/main/java/org/apache/activeio/packet/sync/jxta/JxtaSocketSyncChannelFactory.java b/activeio-jxta/src/main/java/org/apache/activeio/packet/sync/jxta/JxtaSocketSyncChannelFactory.java
index d7f3e3a..68f7076 100644
--- a/activeio-jxta/src/main/java/org/apache/activeio/packet/sync/jxta/JxtaSocketSyncChannelFactory.java
+++ b/activeio-jxta/src/main/java/org/apache/activeio/packet/sync/jxta/JxtaSocketSyncChannelFactory.java
@@ -1,90 +1,90 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.packet.sync.jxta;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.ServerSocket;

-import java.net.Socket;

-import java.net.UnknownHostException;

-

-import javax.net.ServerSocketFactory;

-import javax.net.SocketFactory;

-

-import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;

-import org.p2psockets.P2PServerSocket;

-import org.p2psockets.P2PSocket;

-

-/**

- * A SslSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}

- * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects that use SSL.

- * 

- * @version $Revision$

- */

-public class JxtaSocketSyncChannelFactory extends SocketSyncChannelFactory {

-

-    static public final class JxtaServerSocketFactory extends ServerSocketFactory {

-

-        private static JxtaServerSocketFactory defaultJxtaServerSocketFactory = new JxtaServerSocketFactory();

-        public static ServerSocketFactory getDefault() {

-            return defaultJxtaServerSocketFactory;

-        }

-

-        private JxtaServerSocketFactory() {}        

-        

-        public ServerSocket createServerSocket(int localPort) throws IOException {           

-            return new P2PServerSocket(localPort);

-        }

-

-        public ServerSocket createServerSocket(int localPort, int backlog) throws IOException {

-            return new P2PServerSocket(localPort, backlog);

-        }

-

-        public ServerSocket createServerSocket(int localPort, int backlog, InetAddress localHost) throws IOException {

-            return new P2PServerSocket(localPort, backlog, localHost);

-        }

-    }

-

-    static public final class JxtaSocketFactory extends SocketFactory {

-

-        private static JxtaSocketFactory defaultJxtaSocketFactory = new JxtaSocketFactory();

-        public static SocketFactory getDefault() {

-            return defaultJxtaSocketFactory;

-        }       

-        private JxtaSocketFactory() {}

-        

-        public Socket createSocket(String remoteHost, int remotePort) throws IOException, UnknownHostException {

-            return new P2PSocket(remoteHost, remotePort);

-        }

-

-        public Socket createSocket(String remoteHost, int remotePort, InetAddress localHost, int localPort) throws IOException, UnknownHostException {

-            return new P2PSocket(remoteHost, remotePort, localHost, localPort);

-        }

-

-        public Socket createSocket(InetAddress remoteHost, int remotePort) throws IOException {

-            return new P2PSocket(remoteHost, remotePort);

-        }

-

-        public Socket createSocket(InetAddress remoteHost, int remotePort, InetAddress localHost, int localPort) throws IOException {

-            return new P2PSocket(remoteHost, remotePort, localHost, localPort);

-        }

-    }

-

-    public JxtaSocketSyncChannelFactory() {

-        super(JxtaSocketFactory.getDefault(), JxtaServerSocketFactory.getDefault());

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.packet.sync.jxta;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+import javax.net.ServerSocketFactory;
+import javax.net.SocketFactory;
+
+import org.apache.activeio.packet.sync.socket.SocketSyncChannelFactory;
+import org.p2psockets.P2PServerSocket;
+import org.p2psockets.P2PSocket;
+
+/**
+ * A SslSynchChannelFactory creates {@see org.apache.activeio.net.TcpSynchChannel}
+ * and {@see org.apache.activeio.net.TcpSynchChannelServer} objects that use SSL.
+ * 
+ * @version $Revision$
+ */
+public class JxtaSocketSyncChannelFactory extends SocketSyncChannelFactory {
+
+    static public final class JxtaServerSocketFactory extends ServerSocketFactory {
+
+        private static JxtaServerSocketFactory defaultJxtaServerSocketFactory = new JxtaServerSocketFactory();
+        public static ServerSocketFactory getDefault() {
+            return defaultJxtaServerSocketFactory;
+        }
+
+        private JxtaServerSocketFactory() {}        
+        
+        public ServerSocket createServerSocket(int localPort) throws IOException {           
+            return new P2PServerSocket(localPort);
+        }
+
+        public ServerSocket createServerSocket(int localPort, int backlog) throws IOException {
+            return new P2PServerSocket(localPort, backlog);
+        }
+
+        public ServerSocket createServerSocket(int localPort, int backlog, InetAddress localHost) throws IOException {
+            return new P2PServerSocket(localPort, backlog, localHost);
+        }
+    }
+
+    static public final class JxtaSocketFactory extends SocketFactory {
+
+        private static JxtaSocketFactory defaultJxtaSocketFactory = new JxtaSocketFactory();
+        public static SocketFactory getDefault() {
+            return defaultJxtaSocketFactory;
+        }       
+        private JxtaSocketFactory() {}
+        
+        public Socket createSocket(String remoteHost, int remotePort) throws IOException, UnknownHostException {
+            return new P2PSocket(remoteHost, remotePort);
+        }
+
+        public Socket createSocket(String remoteHost, int remotePort, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
+            return new P2PSocket(remoteHost, remotePort, localHost, localPort);
+        }
+
+        public Socket createSocket(InetAddress remoteHost, int remotePort) throws IOException {
+            return new P2PSocket(remoteHost, remotePort);
+        }
+
+        public Socket createSocket(InetAddress remoteHost, int remotePort, InetAddress localHost, int localPort) throws IOException {
+            return new P2PSocket(remoteHost, remotePort, localHost, localPort);
+        }
+    }
+
+    public JxtaSocketSyncChannelFactory() {
+        super(JxtaSocketFactory.getDefault(), JxtaServerSocketFactory.getDefault());
+    }
+}
diff --git a/activeio-oneport-jetty/src/main/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListener.java b/activeio-oneport-jetty/src/main/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListener.java
index 893a28e..e580a64 100644
--- a/activeio-oneport-jetty/src/main/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListener.java
+++ b/activeio-oneport-jetty/src/main/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListener.java
@@ -1,53 +1,53 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.jetty;

-

-import java.io.IOException;

-import java.net.ServerSocket;

-

-import org.apache.activeio.adapter.AsyncToSyncChannelServer;

-import org.apache.activeio.adapter.SyncChannelServerToServerSocket;

-import org.apache.activeio.oneport.HttpRecognizer;

-import org.apache.activeio.oneport.OnePortAsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.mortbay.http.SocketListener;

-import org.mortbay.util.InetAddrPort;

-

-/**

- *

- */

-public class JettyOnePortSocketListener extends SocketListener {

-

-    private static final long serialVersionUID = 3257567321504561206L;

-    

-    private final OnePortAsyncChannelServer channelServer;

-

-    public JettyOnePortSocketListener(OnePortAsyncChannelServer channelServer) {

-        this.channelServer = channelServer;

-    }

-

-    public JettyOnePortSocketListener(OnePortAsyncChannelServer channelServer, InetAddrPort arg0) {

-        super(arg0);

-        this.channelServer = channelServer;

-    }

-    

-    protected ServerSocket newServerSocket(InetAddrPort addrPort, int backlog) throws IOException {

-       SyncChannelServer syncServer = AsyncToSyncChannelServer.adapt(channelServer.bindAsyncChannel(HttpRecognizer.HTTP_RECOGNIZER));

-       syncServer.start();

-       return new SyncChannelServerToServerSocket(syncServer);

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.jetty;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+
+import org.apache.activeio.adapter.AsyncToSyncChannelServer;
+import org.apache.activeio.adapter.SyncChannelServerToServerSocket;
+import org.apache.activeio.oneport.HttpRecognizer;
+import org.apache.activeio.oneport.OnePortAsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.mortbay.http.SocketListener;
+import org.mortbay.util.InetAddrPort;
+
+/**
+ *
+ */
+public class JettyOnePortSocketListener extends SocketListener {
+
+    private static final long serialVersionUID = 3257567321504561206L;
+    
+    private final OnePortAsyncChannelServer channelServer;
+
+    public JettyOnePortSocketListener(OnePortAsyncChannelServer channelServer) {
+        this.channelServer = channelServer;
+    }
+
+    public JettyOnePortSocketListener(OnePortAsyncChannelServer channelServer, InetAddrPort arg0) {
+        super(arg0);
+        this.channelServer = channelServer;
+    }
+    
+    protected ServerSocket newServerSocket(InetAddrPort addrPort, int backlog) throws IOException {
+       SyncChannelServer syncServer = AsyncToSyncChannelServer.adapt(channelServer.bindAsyncChannel(HttpRecognizer.HTTP_RECOGNIZER));
+       syncServer.start();
+       return new SyncChannelServerToServerSocket(syncServer);
+    }
+}
diff --git a/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListenerTest.java b/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListenerTest.java
index f08af83..6ea508a 100644
--- a/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListenerTest.java
+++ b/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/JettyOnePortSocketListenerTest.java
@@ -1,65 +1,65 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.jetty;

-

-import org.apache.activeio.oneport.OnePortAsyncChannelServerTest;

-import org.apache.activeio.oneport.jetty.JettyOnePortSocketListener;

-import org.mortbay.http.HttpContext;

-import org.mortbay.http.HttpServer;

-import org.mortbay.jetty.servlet.ServletHandler;

-

-import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;

-

-/**

- * 

- */

-public class JettyOnePortSocketListenerTest extends OnePortAsyncChannelServerTest {

-

-    static public BlockingQueue staticResultSlot;

-

-    private HttpServer jetty;

-

-    protected void startHTTPServer() throws Exception {

-        staticResultSlot = resultSlot;

-

-        // Create the server

-        jetty = new HttpServer();

-

-        // Create a port listener

-        JettyOnePortSocketListener listener = new JettyOnePortSocketListener(server);

-        jetty.addListener(listener);

-

-        // Create a context

-        HttpContext context = new HttpContext();

-        context.setContextPath("/");

-        jetty.addContext(context);

-

-        // Create a servlet container

-        ServletHandler servlets = new ServletHandler();

-        context.addHandler(servlets);

-

-        // Map a servlet onto the container

-        servlets.addServlet("Test", "*", TestServlet.class.getName());

-

-        // Start the http server

-        jetty.start();

-    }

-

-    protected void stopHTTPServer() throws InterruptedException {

-        jetty.stop();

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.jetty;
+
+import org.apache.activeio.oneport.OnePortAsyncChannelServerTest;
+import org.apache.activeio.oneport.jetty.JettyOnePortSocketListener;
+import org.mortbay.http.HttpContext;
+import org.mortbay.http.HttpServer;
+import org.mortbay.jetty.servlet.ServletHandler;
+
+import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;
+
+/**
+ * 
+ */
+public class JettyOnePortSocketListenerTest extends OnePortAsyncChannelServerTest {
+
+    static public BlockingQueue staticResultSlot;
+
+    private HttpServer jetty;
+
+    protected void startHTTPServer() throws Exception {
+        staticResultSlot = resultSlot;
+
+        // Create the server
+        jetty = new HttpServer();
+
+        // Create a port listener
+        JettyOnePortSocketListener listener = new JettyOnePortSocketListener(server);
+        jetty.addListener(listener);
+
+        // Create a context
+        HttpContext context = new HttpContext();
+        context.setContextPath("/");
+        jetty.addContext(context);
+
+        // Create a servlet container
+        ServletHandler servlets = new ServletHandler();
+        context.addHandler(servlets);
+
+        // Map a servlet onto the container
+        servlets.addServlet("Test", "*", TestServlet.class.getName());
+
+        // Start the http server
+        jetty.start();
+    }
+
+    protected void stopHTTPServer() throws InterruptedException {
+        jetty.stop();
+    }
+}
diff --git a/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/TestServlet.java b/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/TestServlet.java
index daffad3..9d98d84 100644
--- a/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/TestServlet.java
+++ b/activeio-oneport-jetty/src/test/java/org/apache/activeio/oneport/jetty/TestServlet.java
@@ -1,42 +1,42 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.jetty;

-

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-import java.io.IOException;

-

-import javax.servlet.ServletException;

-import javax.servlet.http.HttpServlet;

-import javax.servlet.http.HttpServletRequest;

-import javax.servlet.http.HttpServletResponse;

-

-

-

-public class TestServlet extends HttpServlet {

-    

-    private static final long serialVersionUID = 3257286933137733686L;

-

-    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

-        try {

-            JettyOnePortSocketListenerTest.staticResultSlot.offer("HTTP", 1, TimeUnit.MILLISECONDS);

-            resp.getOutputStream().print("Hello World!");

-        } catch (InterruptedException e) {

-            e.printStackTrace();

-        }            

-    }

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.jetty;
+
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+
+
+public class TestServlet extends HttpServlet {
+    
+    private static final long serialVersionUID = 3257286933137733686L;
+
+    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+        try {
+            JettyOnePortSocketListenerTest.staticResultSlot.offer("HTTP", 1, TimeUnit.MILLISECONDS);
+            resp.getOutputStream().print("Hello World!");
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }            
+    }
 }
\ No newline at end of file
diff --git a/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortFeatureInitializer.java b/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortFeatureInitializer.java
index cc62e18..db665ad 100644
--- a/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortFeatureInitializer.java
+++ b/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortFeatureInitializer.java
@@ -1,40 +1,40 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-import org.omg.PortableInterceptor.ORBInitInfo;

-import org.openorb.orb.pi.FeatureInitInfo;

-import org.openorb.orb.pi.FeatureInitializer;

-

-/**

- * Used to hook in the OpenORBOpenPortSocketFactory into the ORB.

- */

-public class OpenORBOpenPortFeatureInitializer implements FeatureInitializer {

-    

-    static final private ThreadLocal socketFatory = new ThreadLocal();

-    

-    static public void setContextSocketFactory( OpenORBOpenPortSocketFactory sf ) {

-        socketFatory.set(sf);

-    }

-    

-    public void init(ORBInitInfo orbinfo, FeatureInitInfo featureinfo) {

-        OpenORBOpenPortSocketFactory sf = (OpenORBOpenPortSocketFactory) socketFatory.get();

-        if( sf!=null ) {

-            featureinfo.setFeature("IIOP.SocketFactory", sf);                    

-        }

-    }

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+import org.omg.PortableInterceptor.ORBInitInfo;
+import org.openorb.orb.pi.FeatureInitInfo;
+import org.openorb.orb.pi.FeatureInitializer;
+
+/**
+ * Used to hook in the OpenORBOpenPortSocketFactory into the ORB.
+ */
+public class OpenORBOpenPortFeatureInitializer implements FeatureInitializer {
+    
+    static final private ThreadLocal socketFatory = new ThreadLocal();
+    
+    static public void setContextSocketFactory( OpenORBOpenPortSocketFactory sf ) {
+        socketFatory.set(sf);
+    }
+    
+    public void init(ORBInitInfo orbinfo, FeatureInitInfo featureinfo) {
+        OpenORBOpenPortSocketFactory sf = (OpenORBOpenPortSocketFactory) socketFatory.get();
+        if( sf!=null ) {
+            featureinfo.setFeature("IIOP.SocketFactory", sf);                    
+        }
+    }
+}
diff --git a/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortSocketFactory.java b/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortSocketFactory.java
index b79ca3f..a1b62c6 100644
--- a/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortSocketFactory.java
+++ b/activeio-oneport-openorb/src/main/java/org/apache/activeio/oneport/openorb/OpenORBOpenPortSocketFactory.java
@@ -1,58 +1,58 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-import java.io.IOException;

-import java.net.InetAddress;

-import java.net.ServerSocket;

-import java.net.Socket;

-

-import org.apache.activeio.adapter.AsyncToSyncChannelServer;

-import org.apache.activeio.adapter.SyncChannelServerToServerSocket;

-import org.apache.activeio.oneport.IIOPRecognizer;

-import org.apache.activeio.oneport.OnePortAsyncChannelServer;

-import org.apache.activeio.packet.sync.SyncChannelServer;

-import org.openorb.orb.net.SocketFactory;

-

-/**

- * 

- */

-public class OpenORBOpenPortSocketFactory implements SocketFactory {

-

-    private final OnePortAsyncChannelServer channelServer;

-

-    public OpenORBOpenPortSocketFactory(OnePortAsyncChannelServer channelServer) {

-        this.channelServer = channelServer;

-    }

-    

-    /**

-     * Outbound sockets are normal.

-     */

-    public Socket createSocket(InetAddress address, int port) throws IOException {

-        return new Socket(address, port);

-    }

-

-    /**

-     * Server sockets bind against the OnePortAsyncChannelServer.

-     */

-    public ServerSocket createServerSocket(InetAddress address, int port) throws IOException {

-        SyncChannelServer sychServer = AsyncToSyncChannelServer.adapt(channelServer.bindAsyncChannel(IIOPRecognizer.IIOP_RECOGNIZER));

-		sychServer.start();

-		return new SyncChannelServerToServerSocket(sychServer);

-    }

-    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+import org.apache.activeio.adapter.AsyncToSyncChannelServer;
+import org.apache.activeio.adapter.SyncChannelServerToServerSocket;
+import org.apache.activeio.oneport.IIOPRecognizer;
+import org.apache.activeio.oneport.OnePortAsyncChannelServer;
+import org.apache.activeio.packet.sync.SyncChannelServer;
+import org.openorb.orb.net.SocketFactory;
+
+/**
+ * 
+ */
+public class OpenORBOpenPortSocketFactory implements SocketFactory {
+
+    private final OnePortAsyncChannelServer channelServer;
+
+    public OpenORBOpenPortSocketFactory(OnePortAsyncChannelServer channelServer) {
+        this.channelServer = channelServer;
+    }
+    
+    /**
+     * Outbound sockets are normal.
+     */
+    public Socket createSocket(InetAddress address, int port) throws IOException {
+        return new Socket(address, port);
+    }
+
+    /**
+     * Server sockets bind against the OnePortAsyncChannelServer.
+     */
+    public ServerSocket createServerSocket(InetAddress address, int port) throws IOException {
+        SyncChannelServer sychServer = AsyncToSyncChannelServer.adapt(channelServer.bindAsyncChannel(IIOPRecognizer.IIOP_RECOGNIZER));
+		sychServer.start();
+		return new SyncChannelServerToServerSocket(sychServer);
+    }
+    
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/OpenORBOnePortSocketFactoryTest.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/OpenORBOnePortSocketFactoryTest.java
index 0d998d1..b331245 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/OpenORBOnePortSocketFactoryTest.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/OpenORBOnePortSocketFactoryTest.java
@@ -1,90 +1,90 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-import java.rmi.RemoteException;

-import java.util.Properties;

-

-import javax.naming.NamingException;

-

-import org.apache.activeio.oneport.OnePortAsyncChannelServerTest;

-import org.omg.CORBA.ORB;

-import org.omg.CORBA.Object;

-import org.omg.PortableServer.POA;

-import org.omg.PortableServer.POAHelper;

-

-import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;

-

-/**

- * 

- */

-public class OpenORBOnePortSocketFactoryTest extends OnePortAsyncChannelServerTest {

-

-    static public BlockingQueue staticResultSlot;

-    private ORB orb;

-    private String serverRef;

-    private TestIIOPServerImpl testIIOPServer;

-    private POA rootPOA;

-

-    protected void startIIOPServer() throws Exception {

-        staticResultSlot = resultSlot;

-        

-        Properties props = new Properties();        

-        props.setProperty("org.omg.PortableInterceptor.ORBInitializerClass."+OpenORBOpenPortFeatureInitializer.class.getName(), "");

-        props.setProperty("org.omg.CORBA.ORBClass", "org.openorb.orb.core.ORB");

-        props.setProperty("org.omg.CORBA.ORBSingletonClass", "org.openorb.orb.core.ORBSingleton"); 

-

-        OpenORBOpenPortFeatureInitializer.setContextSocketFactory(new OpenORBOpenPortSocketFactory(server));	        

-        orb = ORB.init( new String[]{}, props );

-        OpenORBOpenPortFeatureInitializer.setContextSocketFactory(null);

-        

-        rootPOA = POAHelper.narrow( orb.resolve_initial_references( "RootPOA" ) );

-

-        TestIIOPServerImpl srv = new TestIIOPServerImpl();

-        serverRef = orb.object_to_string( srv._this( orb ) );

-        rootPOA.the_POAManager().activate();

-        new Thread(){

-            public void run() {

-	            orb.run();

-            }

-        }.start();

-    }

-    

-    protected void stopIIOPServer() throws Exception {

-        orb.shutdown(true);

-    }

-    

-    protected void hitIIOPServer( ) throws NamingException, RemoteException

-    {

-        // Create a client side orb.

-        Properties props = new Properties();        

-        props.setProperty("org.omg.CORBA.ORBClass", "org.openorb.orb.core.ORB");

-        props.setProperty("org.omg.CORBA.ORBSingletonClass", "org.openorb.orb.core.ORBSingleton"); 

-        ORB orb = ORB.init( new String[]{}, props );

-        

-        Object obj = orb.string_to_object( serverRef );

-        TestIIOPServer srv = TestIIOPServerHelper.narrow( obj );

-        try {

-            srv.test();

-        } catch (Throwable e) {

-            e.printStackTrace();

-        } finally {

-            orb.shutdown(true);

-        }

-    }

-                    

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+import java.rmi.RemoteException;
+import java.util.Properties;
+
+import javax.naming.NamingException;
+
+import org.apache.activeio.oneport.OnePortAsyncChannelServerTest;
+import org.omg.CORBA.ORB;
+import org.omg.CORBA.Object;
+import org.omg.PortableServer.POA;
+import org.omg.PortableServer.POAHelper;
+
+import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;
+
+/**
+ * 
+ */
+public class OpenORBOnePortSocketFactoryTest extends OnePortAsyncChannelServerTest {
+
+    static public BlockingQueue staticResultSlot;
+    private ORB orb;
+    private String serverRef;
+    private TestIIOPServerImpl testIIOPServer;
+    private POA rootPOA;
+
+    protected void startIIOPServer() throws Exception {
+        staticResultSlot = resultSlot;
+        
+        Properties props = new Properties();        
+        props.setProperty("org.omg.PortableInterceptor.ORBInitializerClass."+OpenORBOpenPortFeatureInitializer.class.getName(), "");
+        props.setProperty("org.omg.CORBA.ORBClass", "org.openorb.orb.core.ORB");
+        props.setProperty("org.omg.CORBA.ORBSingletonClass", "org.openorb.orb.core.ORBSingleton"); 
+
+        OpenORBOpenPortFeatureInitializer.setContextSocketFactory(new OpenORBOpenPortSocketFactory(server));	        
+        orb = ORB.init( new String[]{}, props );
+        OpenORBOpenPortFeatureInitializer.setContextSocketFactory(null);
+        
+        rootPOA = POAHelper.narrow( orb.resolve_initial_references( "RootPOA" ) );
+
+        TestIIOPServerImpl srv = new TestIIOPServerImpl();
+        serverRef = orb.object_to_string( srv._this( orb ) );
+        rootPOA.the_POAManager().activate();
+        new Thread(){
+            public void run() {
+	            orb.run();
+            }
+        }.start();
+    }
+    
+    protected void stopIIOPServer() throws Exception {
+        orb.shutdown(true);
+    }
+    
+    protected void hitIIOPServer( ) throws NamingException, RemoteException
+    {
+        // Create a client side orb.
+        Properties props = new Properties();        
+        props.setProperty("org.omg.CORBA.ORBClass", "org.openorb.orb.core.ORB");
+        props.setProperty("org.omg.CORBA.ORBSingletonClass", "org.openorb.orb.core.ORBSingleton"); 
+        ORB orb = ORB.init( new String[]{}, props );
+        
+        Object obj = orb.string_to_object( serverRef );
+        TestIIOPServer srv = TestIIOPServerHelper.narrow( obj );
+        try {
+            srv.test();
+        } catch (Throwable e) {
+            e.printStackTrace();
+        } finally {
+            orb.shutdown(true);
+        }
+    }
+                    
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServer.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServer.java
index 7d72e1d..2b527cd 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServer.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServer.java
@@ -1,26 +1,26 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-/**

- * Interface definition: TestIIOPServer.

- * 

- * @author OpenORB Compiler

- */

-public interface TestIIOPServer extends TestIIOPServerOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity

-{

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+/**
+ * Interface definition: TestIIOPServer.
+ * 
+ * @author OpenORB Compiler
+ */
+public interface TestIIOPServer extends TestIIOPServerOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
+{
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHelper.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHelper.java
index 12ca746..f43977c 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHelper.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHelper.java
@@ -1,148 +1,148 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-

-/** 

- * Helper class for : TestIIOPServer

- *  

- * @author OpenORB Compiler

- */ 

-public class TestIIOPServerHelper

-{

-    /**

-     * Insert TestIIOPServer into an any

-     * @param a an any

-     * @param t TestIIOPServer value

-     */

-    public static void insert(org.omg.CORBA.Any a, org.apache.activeio.oneport.openorb.TestIIOPServer t)

-    {

-        a.insert_Object(t , type());

-    }

-

-    /**

-     * Extract TestIIOPServer from an any

-     *

-     * @param a an any

-     * @return the extracted TestIIOPServer value

-     */

-    public static org.apache.activeio.oneport.openorb.TestIIOPServer extract( org.omg.CORBA.Any a )

-    {

-        if ( !a.type().equivalent( type() ) )

-        {

-            throw new org.omg.CORBA.MARSHAL();

-        }

-        try

-        {

-            return org.apache.activeio.oneport.openorb.TestIIOPServerHelper.narrow( a.extract_Object() );

-        }

-        catch ( final org.omg.CORBA.BAD_PARAM e )

-        {

-            throw new org.omg.CORBA.MARSHAL(e.getMessage());

-        }

-    }

-

-    //

-    // Internal TypeCode value

-    //

-    private static org.omg.CORBA.TypeCode _tc = null;

-

-    /**

-     * Return the TestIIOPServer TypeCode

-     * @return a TypeCode

-     */

-    public static org.omg.CORBA.TypeCode type()

-    {

-        if (_tc == null) {

-            org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();

-            _tc = orb.create_interface_tc( id(), "TestIIOPServer" );

-        }

-        return _tc;

-    }

-

-    /**

-     * Return the TestIIOPServer IDL ID

-     * @return an ID

-     */

-    public static String id()

-    {

-        return _id;

-    }

-

-    private final static String _id = "IDL:org/activeio/oneport/TestIIOPServer:1.0";

-

-    /**

-     * Read TestIIOPServer from a marshalled stream

-     * @param istream the input stream

-     * @return the readed TestIIOPServer value

-     */

-    public static org.apache.activeio.oneport.openorb.TestIIOPServer read(org.omg.CORBA.portable.InputStream istream)

-    {

-        return(org.apache.activeio.oneport.openorb.TestIIOPServer)istream.read_Object(org.apache.activeio.oneport.openorb._TestIIOPServerStub.class);

-    }

-

-    /**

-     * Write TestIIOPServer into a marshalled stream

-     * @param ostream the output stream

-     * @param value TestIIOPServer value

-     */

-    public static void write(org.omg.CORBA.portable.OutputStream ostream, org.apache.activeio.oneport.openorb.TestIIOPServer value)

-    {

-        ostream.write_Object((org.omg.CORBA.portable.ObjectImpl)value);

-    }

-

-    /**

-     * Narrow CORBA::Object to TestIIOPServer

-     * @param obj the CORBA Object

-     * @return TestIIOPServer Object

-     */

-    public static TestIIOPServer narrow(org.omg.CORBA.Object obj)

-    {

-        if (obj == null)

-            return null;

-        if (obj instanceof TestIIOPServer)

-            return (TestIIOPServer)obj;

-

-        if (obj._is_a(id()))

-        {

-            _TestIIOPServerStub stub = new _TestIIOPServerStub();

-            stub._set_delegate(((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate());

-            return stub;

-        }

-

-        throw new org.omg.CORBA.BAD_PARAM();

-    }

-

-    /**

-     * Unchecked Narrow CORBA::Object to TestIIOPServer

-     * @param obj the CORBA Object

-     * @return TestIIOPServer Object

-     */

-    public static TestIIOPServer unchecked_narrow(org.omg.CORBA.Object obj)

-    {

-        if (obj == null)

-            return null;

-        if (obj instanceof TestIIOPServer)

-            return (TestIIOPServer)obj;

-

-        _TestIIOPServerStub stub = new _TestIIOPServerStub();

-        stub._set_delegate(((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate());

-        return stub;

-

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+
+/** 
+ * Helper class for : TestIIOPServer
+ *  
+ * @author OpenORB Compiler
+ */ 
+public class TestIIOPServerHelper
+{
+    /**
+     * Insert TestIIOPServer into an any
+     * @param a an any
+     * @param t TestIIOPServer value
+     */
+    public static void insert(org.omg.CORBA.Any a, org.apache.activeio.oneport.openorb.TestIIOPServer t)
+    {
+        a.insert_Object(t , type());
+    }
+
+    /**
+     * Extract TestIIOPServer from an any
+     *
+     * @param a an any
+     * @return the extracted TestIIOPServer value
+     */
+    public static org.apache.activeio.oneport.openorb.TestIIOPServer extract( org.omg.CORBA.Any a )
+    {
+        if ( !a.type().equivalent( type() ) )
+        {
+            throw new org.omg.CORBA.MARSHAL();
+        }
+        try
+        {
+            return org.apache.activeio.oneport.openorb.TestIIOPServerHelper.narrow( a.extract_Object() );
+        }
+        catch ( final org.omg.CORBA.BAD_PARAM e )
+        {
+            throw new org.omg.CORBA.MARSHAL(e.getMessage());
+        }
+    }
+
+    //
+    // Internal TypeCode value
+    //
+    private static org.omg.CORBA.TypeCode _tc = null;
+
+    /**
+     * Return the TestIIOPServer TypeCode
+     * @return a TypeCode
+     */
+    public static org.omg.CORBA.TypeCode type()
+    {
+        if (_tc == null) {
+            org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
+            _tc = orb.create_interface_tc( id(), "TestIIOPServer" );
+        }
+        return _tc;
+    }
+
+    /**
+     * Return the TestIIOPServer IDL ID
+     * @return an ID
+     */
+    public static String id()
+    {
+        return _id;
+    }
+
+    private final static String _id = "IDL:org/activeio/oneport/TestIIOPServer:1.0";
+
+    /**
+     * Read TestIIOPServer from a marshalled stream
+     * @param istream the input stream
+     * @return the readed TestIIOPServer value
+     */
+    public static org.apache.activeio.oneport.openorb.TestIIOPServer read(org.omg.CORBA.portable.InputStream istream)
+    {
+        return(org.apache.activeio.oneport.openorb.TestIIOPServer)istream.read_Object(org.apache.activeio.oneport.openorb._TestIIOPServerStub.class);
+    }
+
+    /**
+     * Write TestIIOPServer into a marshalled stream
+     * @param ostream the output stream
+     * @param value TestIIOPServer value
+     */
+    public static void write(org.omg.CORBA.portable.OutputStream ostream, org.apache.activeio.oneport.openorb.TestIIOPServer value)
+    {
+        ostream.write_Object((org.omg.CORBA.portable.ObjectImpl)value);
+    }
+
+    /**
+     * Narrow CORBA::Object to TestIIOPServer
+     * @param obj the CORBA Object
+     * @return TestIIOPServer Object
+     */
+    public static TestIIOPServer narrow(org.omg.CORBA.Object obj)
+    {
+        if (obj == null)
+            return null;
+        if (obj instanceof TestIIOPServer)
+            return (TestIIOPServer)obj;
+
+        if (obj._is_a(id()))
+        {
+            _TestIIOPServerStub stub = new _TestIIOPServerStub();
+            stub._set_delegate(((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate());
+            return stub;
+        }
+
+        throw new org.omg.CORBA.BAD_PARAM();
+    }
+
+    /**
+     * Unchecked Narrow CORBA::Object to TestIIOPServer
+     * @param obj the CORBA Object
+     * @return TestIIOPServer Object
+     */
+    public static TestIIOPServer unchecked_narrow(org.omg.CORBA.Object obj)
+    {
+        if (obj == null)
+            return null;
+        if (obj instanceof TestIIOPServer)
+            return (TestIIOPServer)obj;
+
+        _TestIIOPServerStub stub = new _TestIIOPServerStub();
+        stub._set_delegate(((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate());
+        return stub;
+
+    }
+
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHolder.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHolder.java
index ccd9e87..868ba4a 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHolder.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerHolder.java
@@ -1,74 +1,74 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-/**

- * Holder class for : TestIIOPServer

- * 

- * @author OpenORB Compiler

- */

-final public class TestIIOPServerHolder

-        implements org.omg.CORBA.portable.Streamable

-{

-    /**

-     * Internal TestIIOPServer value

-     */

-    public org.apache.activeio.oneport.openorb.TestIIOPServer value;

-

-    /**

-     * Default constructor

-     */

-    public TestIIOPServerHolder()

-    { }

-

-    /**

-     * Constructor with value initialisation

-     * @param initial the initial value

-     */

-    public TestIIOPServerHolder(org.apache.activeio.oneport.openorb.TestIIOPServer initial)

-    {

-        value = initial;

-    }

-

-    /**

-     * Read TestIIOPServer from a marshalled stream

-     * @param istream the input stream

-     */

-    public void _read(org.omg.CORBA.portable.InputStream istream)

-    {

-        value = TestIIOPServerHelper.read(istream);

-    }

-

-    /**

-     * Write TestIIOPServer into a marshalled stream

-     * @param ostream the output stream

-     */

-    public void _write(org.omg.CORBA.portable.OutputStream ostream)

-    {

-        TestIIOPServerHelper.write(ostream,value);

-    }

-

-    /**

-     * Return the TestIIOPServer TypeCode

-     * @return a TypeCode

-     */

-    public org.omg.CORBA.TypeCode _type()

-    {

-        return TestIIOPServerHelper.type();

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+/**
+ * Holder class for : TestIIOPServer
+ * 
+ * @author OpenORB Compiler
+ */
+final public class TestIIOPServerHolder
+        implements org.omg.CORBA.portable.Streamable
+{
+    /**
+     * Internal TestIIOPServer value
+     */
+    public org.apache.activeio.oneport.openorb.TestIIOPServer value;
+
+    /**
+     * Default constructor
+     */
+    public TestIIOPServerHolder()
+    { }
+
+    /**
+     * Constructor with value initialisation
+     * @param initial the initial value
+     */
+    public TestIIOPServerHolder(org.apache.activeio.oneport.openorb.TestIIOPServer initial)
+    {
+        value = initial;
+    }
+
+    /**
+     * Read TestIIOPServer from a marshalled stream
+     * @param istream the input stream
+     */
+    public void _read(org.omg.CORBA.portable.InputStream istream)
+    {
+        value = TestIIOPServerHelper.read(istream);
+    }
+
+    /**
+     * Write TestIIOPServer into a marshalled stream
+     * @param ostream the output stream
+     */
+    public void _write(org.omg.CORBA.portable.OutputStream ostream)
+    {
+        TestIIOPServerHelper.write(ostream,value);
+    }
+
+    /**
+     * Return the TestIIOPServer TypeCode
+     * @return a TypeCode
+     */
+    public org.omg.CORBA.TypeCode _type()
+    {
+        return TestIIOPServerHelper.type();
+    }
+
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerImpl.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerImpl.java
index 9530886..e55c040 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerImpl.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerImpl.java
@@ -1,32 +1,32 @@
-

-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;

-

-/**

- * 

- */

-public class TestIIOPServerImpl extends TestIIOPServerPOA {

-    public void test() {

-        try {

-            OpenORBOnePortSocketFactoryTest.staticResultSlot.offer("IIOP", 1, TimeUnit.MILLISECONDS);

-        } catch (InterruptedException e) {

-        }

-    }

-}

+
+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+
+/**
+ * 
+ */
+public class TestIIOPServerImpl extends TestIIOPServerPOA {
+    public void test() {
+        try {
+            OpenORBOnePortSocketFactoryTest.staticResultSlot.offer("IIOP", 1, TimeUnit.MILLISECONDS);
+        } catch (InterruptedException e) {
+        }
+    }
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerOperations.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerOperations.java
index b7e58db..62c62e1 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerOperations.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerOperations.java
@@ -1,31 +1,31 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-/**

- * Interface definition: TestIIOPServer.

- * 

- * @author OpenORB Compiler

- */

-public interface TestIIOPServerOperations

-{

-    /**

-     * Operation test

-     */

-    public void test();

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+/**
+ * Interface definition: TestIIOPServer.
+ * 
+ * @author OpenORB Compiler
+ */
+public interface TestIIOPServerOperations
+{
+    /**
+     * Operation test
+     */
+    public void test();
+
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOA.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOA.java
index 4ad9a70..0341fef 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOA.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOA.java
@@ -1,72 +1,72 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-/**

- * Interface definition: TestIIOPServer.

- * 

- * @author OpenORB Compiler

- */

-public abstract class TestIIOPServerPOA extends org.omg.PortableServer.Servant

-        implements TestIIOPServerOperations, org.omg.CORBA.portable.InvokeHandler

-{

-    public TestIIOPServer _this()

-    {

-        return TestIIOPServerHelper.narrow(_this_object());

-    }

-

-    public TestIIOPServer _this(org.omg.CORBA.ORB orb)

-    {

-        return TestIIOPServerHelper.narrow(_this_object(orb));

-    }

-

-    private static String [] _ids_list =

-    {

-        "IDL:org/activeio/oneport/TestIIOPServer:1.0"

-    };

-

-    public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte [] objectId)

-    {

-        return _ids_list;

-    }

-

-    public final org.omg.CORBA.portable.OutputStream _invoke(final String opName,

-            final org.omg.CORBA.portable.InputStream _is,

-            final org.omg.CORBA.portable.ResponseHandler handler)

-    {

-

-        if (opName.equals("test")) {

-                return _invoke_test(_is, handler);

-        } else {

-            throw new org.omg.CORBA.BAD_OPERATION(opName);

-        }

-    }

-

-    // helper methods

-    private org.omg.CORBA.portable.OutputStream _invoke_test(

-            final org.omg.CORBA.portable.InputStream _is,

-            final org.omg.CORBA.portable.ResponseHandler handler) {

-        org.omg.CORBA.portable.OutputStream _output;

-

-        test();

-

-        _output = handler.createReply();

-

-        return _output;

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+/**
+ * Interface definition: TestIIOPServer.
+ * 
+ * @author OpenORB Compiler
+ */
+public abstract class TestIIOPServerPOA extends org.omg.PortableServer.Servant
+        implements TestIIOPServerOperations, org.omg.CORBA.portable.InvokeHandler
+{
+    public TestIIOPServer _this()
+    {
+        return TestIIOPServerHelper.narrow(_this_object());
+    }
+
+    public TestIIOPServer _this(org.omg.CORBA.ORB orb)
+    {
+        return TestIIOPServerHelper.narrow(_this_object(orb));
+    }
+
+    private static String [] _ids_list =
+    {
+        "IDL:org/activeio/oneport/TestIIOPServer:1.0"
+    };
+
+    public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte [] objectId)
+    {
+        return _ids_list;
+    }
+
+    public final org.omg.CORBA.portable.OutputStream _invoke(final String opName,
+            final org.omg.CORBA.portable.InputStream _is,
+            final org.omg.CORBA.portable.ResponseHandler handler)
+    {
+
+        if (opName.equals("test")) {
+                return _invoke_test(_is, handler);
+        } else {
+            throw new org.omg.CORBA.BAD_OPERATION(opName);
+        }
+    }
+
+    // helper methods
+    private org.omg.CORBA.portable.OutputStream _invoke_test(
+            final org.omg.CORBA.portable.InputStream _is,
+            final org.omg.CORBA.portable.ResponseHandler handler) {
+        org.omg.CORBA.portable.OutputStream _output;
+
+        test();
+
+        _output = handler.createReply();
+
+        return _output;
+    }
+
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOATie.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOATie.java
index 165de98..6b76286 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOATie.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/TestIIOPServerPOATie.java
@@ -1,89 +1,89 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-/**

- * Interface definition: TestIIOPServer.

- * 

- * @author OpenORB Compiler

- */

-public class TestIIOPServerPOATie extends TestIIOPServerPOA

-{

-

-    //

-    // Private reference to implementation object

-    //

-    private TestIIOPServerOperations _tie;

-

-    //

-    // Private reference to POA

-    //

-    private org.omg.PortableServer.POA _poa;

-

-    /**

-     * Constructor

-     */

-    public TestIIOPServerPOATie(TestIIOPServerOperations tieObject)

-    {

-        _tie = tieObject;

-    }

-

-    /**

-     * Constructor

-     */

-    public TestIIOPServerPOATie(TestIIOPServerOperations tieObject, org.omg.PortableServer.POA poa)

-    {

-        _tie = tieObject;

-        _poa = poa;

-    }

-

-    /**

-     * Get the delegate

-     */

-    public TestIIOPServerOperations _delegate()

-    {

-        return _tie;

-    }

-

-    /**

-     * Set the delegate

-     */

-    public void _delegate(TestIIOPServerOperations delegate_)

-    {

-        _tie = delegate_;

-    }

-

-    /**

-     * _default_POA method

-     */

-    public org.omg.PortableServer.POA _default_POA()

-    {

-        if (_poa != null)

-            return _poa;

-        else

-            return super._default_POA();

-    }

-

-    /**

-     * Operation test

-     */

-    public void test()

-    {

-        _tie.test();

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+/**
+ * Interface definition: TestIIOPServer.
+ * 
+ * @author OpenORB Compiler
+ */
+public class TestIIOPServerPOATie extends TestIIOPServerPOA
+{
+
+    //
+    // Private reference to implementation object
+    //
+    private TestIIOPServerOperations _tie;
+
+    //
+    // Private reference to POA
+    //
+    private org.omg.PortableServer.POA _poa;
+
+    /**
+     * Constructor
+     */
+    public TestIIOPServerPOATie(TestIIOPServerOperations tieObject)
+    {
+        _tie = tieObject;
+    }
+
+    /**
+     * Constructor
+     */
+    public TestIIOPServerPOATie(TestIIOPServerOperations tieObject, org.omg.PortableServer.POA poa)
+    {
+        _tie = tieObject;
+        _poa = poa;
+    }
+
+    /**
+     * Get the delegate
+     */
+    public TestIIOPServerOperations _delegate()
+    {
+        return _tie;
+    }
+
+    /**
+     * Set the delegate
+     */
+    public void _delegate(TestIIOPServerOperations delegate_)
+    {
+        _tie = delegate_;
+    }
+
+    /**
+     * _default_POA method
+     */
+    public org.omg.PortableServer.POA _default_POA()
+    {
+        if (_poa != null)
+            return _poa;
+        else
+            return super._default_POA();
+    }
+
+    /**
+     * Operation test
+     */
+    public void test()
+    {
+        _tie.test();
+    }
+
+}
diff --git a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/_TestIIOPServerStub.java b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/_TestIIOPServerStub.java
index 5f00427..d6474ab 100644
--- a/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/_TestIIOPServerStub.java
+++ b/activeio-oneport-openorb/src/test/java/org/apache/activeio/oneport/openorb/_TestIIOPServerStub.java
@@ -1,89 +1,89 @@
-/**

- *

- * Copyright 2005-2006 The Apache Software Foundation

- *

- * Licensed 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.

- */

-package org.apache.activeio.oneport.openorb;

-

-

-/**

- * Interface definition: TestIIOPServer.

- * 

- * @author OpenORB Compiler

- */

-public class _TestIIOPServerStub extends org.omg.CORBA.portable.ObjectImpl

-        implements TestIIOPServer

-{

-    static final String[] _ids_list =

-    {

-        "IDL:org/activeio/oneport/TestIIOPServer:1.0"

-    };

-

-    public String[] _ids()

-    {

-     return _ids_list;

-    }

-

-    private final static Class _opsClass = org.apache.activeio.oneport.openorb.TestIIOPServerOperations.class;

-

-    /**

-     * Operation test

-     */

-    public void test()

-    {

-        while(true)

-        {

-            if (!this._is_local())

-            {

-                org.omg.CORBA.portable.InputStream _input = null;

-                try

-                {

-                    org.omg.CORBA.portable.OutputStream _output = this._request("test",true);

-                    _input = this._invoke(_output);

-                    return;

-                }

-                catch(org.omg.CORBA.portable.RemarshalException _exception)

-                {

-                    continue;

-                }

-                catch(org.omg.CORBA.portable.ApplicationException _exception)

-                {

-                    String _exception_id = _exception.getId();

-                    throw new org.omg.CORBA.UNKNOWN("Unexpected User Exception: "+ _exception_id);

-                }

-                finally

-                {

-                    this._releaseReply(_input);

-                }

-            }

-            else

-            {

-                org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke("test",_opsClass);

-                if (_so == null)

-                   continue;

-                org.apache.activeio.oneport.openorb.TestIIOPServerOperations _self = (org.apache.activeio.oneport.openorb.TestIIOPServerOperations) _so.servant;

-                try

-                {

-                    _self.test();

-                    return;

-                }

-                finally

-                {

-                    _servant_postinvoke(_so);

-                }

-            }

-        }

-    }

-

-}

+/**
+ *
+ * Copyright 2005-2006 The Apache Software Foundation
+ *
+ * Licensed 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.
+ */
+package org.apache.activeio.oneport.openorb;
+
+
+/**
+ * Interface definition: TestIIOPServer.
+ * 
+ * @author OpenORB Compiler
+ */
+public class _TestIIOPServerStub extends org.omg.CORBA.portable.ObjectImpl
+        implements TestIIOPServer
+{
+    static final String[] _ids_list =
+    {
+        "IDL:org/activeio/oneport/TestIIOPServer:1.0"
+    };
+
+    public String[] _ids()
+    {
+     return _ids_list;
+    }
+
+    private final static Class _opsClass = org.apache.activeio.oneport.openorb.TestIIOPServerOperations.class;
+
+    /**
+     * Operation test
+     */
+    public void test()
+    {
+        while(true)
+        {
+            if (!this._is_local())
+            {
+                org.omg.CORBA.portable.InputStream _input = null;
+                try
+                {
+                    org.omg.CORBA.portable.OutputStream _output = this._request("test",true);
+                    _input = this._invoke(_output);
+                    return;
+                }
+                catch(org.omg.CORBA.portable.RemarshalException _exception)
+                {
+                    continue;
+                }
+                catch(org.omg.CORBA.portable.ApplicationException _exception)
+                {
+                    String _exception_id = _exception.getId();
+                    throw new org.omg.CORBA.UNKNOWN("Unexpected User Exception: "+ _exception_id);
+                }
+                finally
+                {
+                    this._releaseReply(_input);
+                }
+            }
+            else
+            {
+                org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke("test",_opsClass);
+                if (_so == null)
+                   continue;
+                org.apache.activeio.oneport.openorb.TestIIOPServerOperations _self = (org.apache.activeio.oneport.openorb.TestIIOPServerOperations) _so.servant;
+                try
+                {
+                    _self.test();
+                    return;
+                }
+                finally
+                {
+                    _servant_postinvoke(_so);
+                }
+            }
+        }
+    }
+
+}