FELIX-615 Add remote shell contributed by Dieter Wimberger

git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@687053 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/shell.remote/LICENSE b/shell.remote/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/shell.remote/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/shell.remote/NOTICE b/shell.remote/NOTICE
new file mode 100644
index 0000000..4774f20
--- /dev/null
+++ b/shell.remote/NOTICE
@@ -0,0 +1,28 @@
+Apache Felix Remote Shell
+Copyright 2006-2008 Dieter Wimberger
+
+
+I. Included Software
+
+Apache Felix Remote Shell has been initially developped by Dieter Wimberger.
+Copyright (c) 2008 Dieter Wimberger
+Licensed under the Apache License 2.0.
+
+This product includes software developed at
+The OSGi Alliance (http://www.osgi.org/).
+Copyright 2006 The OSGi Alliance.
+Licensed under the Apache License 2.0.
+
+
+II. Used Software
+
+This product uses software developed at
+The Apache Software Foundation (http://www.apache.org/).
+
+This product uses software developed at
+The OSGi Alliance (http://www.osgi.org/).
+Copyright 2006 The OSGi Alliance.
+Licensed under the Apache License 2.0.
+
+III. License Summary
+- Apache License 2.0
\ No newline at end of file
diff --git a/shell.remote/pom.xml b/shell.remote/pom.xml
new file mode 100644
index 0000000..85392d4
--- /dev/null
+++ b/shell.remote/pom.xml
@@ -0,0 +1,87 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+    
+    http://www.apache.org/licenses/LICENSE-2.0
+    
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>felix</artifactId>
+        <version>1.0.2</version>
+        <relativePath>../pom/pom.xml</relativePath>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <packaging>bundle</packaging>
+    <name>Apache Felix Remote Shell</name>
+    <description>
+        A simple remote textual user interface for Felix' shell service.
+    </description>
+    <version>0.9.0-SNAPSHOT</version>
+    <artifactId>org.apache.felix.shell.remote</artifactId>
+    <dependencies>
+        <dependency>
+            <groupId>${pom.groupId}</groupId>
+            <artifactId>org.osgi.core</artifactId>
+            <version>1.0.0</version>
+        </dependency>
+        <dependency>
+            <groupId>${pom.groupId}</groupId>
+            <artifactId>org.osgi.compendium</artifactId>
+            <version>1.0.1</version>
+        </dependency>
+        <dependency>
+            <groupId>${pom.groupId}</groupId>
+            <artifactId>org.apache.felix.shell</artifactId>
+            <version>1.0.0</version>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Private-Package>
+                            org.apache.felix.shell.remote.*
+                        </Private-Package>
+                        <Bundle-Category>console</Bundle-Category>
+                        <Bundle-Activator>
+                            org.apache.felix.shell.remote.Activator
+                        </Bundle-Activator>
+                        <Bundle-SymbolicName>
+                            ${pom.artifactId}
+                        </Bundle-SymbolicName>
+                        <Bundle-Vendor>
+                            The Apache Software Foundation
+                        </Bundle-Vendor>
+                        <Bundle-Copyright>
+                            Dieter Wimberger
+                        </Bundle-Copyright>
+                        <Import-Service>
+                            org.apache.felix.shell.ShellService
+                        </Import-Service>
+                        <Import-Service>
+                            org.osgi.service.log.LogService
+                        </Import-Service>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/Activator.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/Activator.java
new file mode 100644
index 0000000..d418b82
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/Activator.java
@@ -0,0 +1,73 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+
+/**
+ * Activator for the telnet console.
+ *
+ * @author Dieter Wimberger (wimpi)
+ */
+public class Activator implements BundleActivator
+{
+
+    private static ServiceMediator c_Services;
+    private Listener m_Listener;
+
+
+    public void start( BundleContext bundleContext ) throws Exception
+    {
+        //1. Prepare mediator
+        c_Services = new ServiceMediator();
+        c_Services.activate( bundleContext );
+
+        //2. Prepare the listener
+        m_Listener = new Listener();
+        m_Listener.activate();
+    }
+
+
+    public void stop( BundleContext bundleContext ) throws Exception
+    {
+        if ( m_Listener != null )
+        {
+            m_Listener.deactivate();
+            m_Listener = null;
+        }
+        if ( c_Services != null )
+        {
+            c_Services.deactivate();
+            c_Services = null;
+        }
+    }
+
+
+    /**
+     * Returns a reference to the {@link ServiceMediator} instance used in this bundle.
+     *
+     * @return a {@link ServiceMediator} instance.
+     */
+    public static ServiceMediator getServices()
+    {
+        return c_Services;
+    }
+
+}
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/AtomicInteger.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/AtomicInteger.java
new file mode 100644
index 0000000..79a79f5
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/AtomicInteger.java
@@ -0,0 +1,93 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+/**
+ * Provides an atomic integer.
+ * <p/>
+ *
+ * @author Dieter Wimberger (wimpi)
+ */
+class AtomicInteger
+{
+
+    private int m_Value;
+
+
+    public AtomicInteger()
+    {
+        m_Value = 0;
+    }//constructor
+
+
+    /**
+     * Constructs a new <tt>AtomicInteger</tt>
+     * with a given initial value.
+     *
+     * @param value the initial value.
+     */
+    public AtomicInteger( int value )
+    {
+        m_Value = value;
+    }//constructor
+
+
+    /**
+     * Increments this <tt>AtomicInteger</tt> by one.
+     *
+     * @return the resulting value.
+     */
+    public synchronized int increment()
+    {
+        return ++m_Value;
+    }//increment
+
+
+    /**
+     * Decrements this <tt>AtomicInteger</tt> by one.
+     *
+     * @return the resulting value.
+     */
+    public synchronized int decrement()
+    {
+        return --m_Value;
+    }//decrement
+
+
+    /**
+     * Sets the value of this <tt>AtomicInteger</tt>.
+     *
+     * @param i the new value.
+     */
+    public synchronized void set( int i )
+    {
+        m_Value = i;
+    }//set
+
+
+    /**
+     * Returns the value of this <tt>AtomicInteger</tt>.
+     *
+     * @return the actual value.
+     */
+    public synchronized int get()
+    {
+        return m_Value;
+    }//get
+
+}//class AtomicInteger
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/Latch.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/Latch.java
new file mode 100644
index 0000000..49f7507
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/Latch.java
@@ -0,0 +1,120 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+/**
+ * A latch is a boolean condition that is set at most once, ever.
+ * Once a single release is issued, all acquires will pass.
+ * <p/>
+ * <b>Sample usage.</b> Here are a set of classes that use
+ * a latch as a start signal for a group of worker threads that
+ * are created and started beforehand, and then later enabled.
+ * <pre>
+ * class Worker implements Runnable {
+ *   private final Latch startSignal;
+ *   Worker(Latch l) { startSignal = l; }
+ *    public void run() {
+ *      startSignal.acquire();
+ *      doWork();
+ *   }
+ *   void doWork() { ... }
+ * }
+ * <p/>
+ * class Driver { // ...
+ *   void main() {
+ *     Latch go = new Latch();
+ *     for (int i = 0; i < N; ++i) // make threads
+ *       new Thread(new Worker(go)).start();
+ *     doSomethingElse();         // don't let run yet
+ *     go.release();              // let all threads proceed
+ *   }
+ * }
+ * </pre>
+ *
+ * @author Doug Lea
+ */
+class Latch
+{
+
+    protected boolean latched_ = false;
+
+
+    /*
+      This could use double-check, but doesn't.
+      If the latch is being used as an indicator of
+      the presence or state of an object, the user would
+      not necessarily get the memory barrier that comes with synch
+      that would be needed to correctly use that object. This
+      would lead to errors that users would be very hard to track down. So, to
+      be conservative, we always use synch.
+    */
+
+    public void acquire() throws InterruptedException
+    {
+        if ( Thread.interrupted() )
+            throw new InterruptedException();
+        synchronized ( this )
+        {
+            while ( !latched_ )
+                wait();
+        }
+    }//acquire
+
+
+    public boolean attempt( long msecs ) throws InterruptedException
+    {
+        if ( Thread.interrupted() )
+            throw new InterruptedException();
+        synchronized ( this )
+        {
+            if ( latched_ )
+                return true;
+            else if ( msecs <= 0 )
+                return false;
+            else
+            {
+                long waitTime = msecs;
+                long start = System.currentTimeMillis();
+                for ( ;; )
+                {
+                    wait( waitTime );
+                    if ( latched_ )
+                        return true;
+                    else
+                    {
+                        waitTime = msecs - ( System.currentTimeMillis() - start );
+                        if ( waitTime <= 0 )
+                            return false;
+                    }
+                }
+            }
+        }
+    }//attempt
+
+
+    /**
+     * Enable all current and future acquires to pass *
+     */
+    public synchronized void release()
+    {
+        latched_ = true;
+        notifyAll();
+    }//release
+
+}//class Latch
+
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/Listener.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/Listener.java
new file mode 100644
index 0000000..65db291
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/Listener.java
@@ -0,0 +1,161 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketException;
+
+
+/**
+ * Implements a simple listener that will accept a single connection.
+ * <p/>
+ *
+ * @author Dieter Wimberger (wimpi)
+ */
+class Listener
+{
+
+    private int m_Port;
+    private Thread m_ListenerThread;
+    private boolean m_Stop = false;
+    private ServerSocket m_ServerSocket;
+    private AtomicInteger m_UseCounter;
+    private int m_MaxConnections;
+
+
+    /**
+     * Activates this listener on a listener thread (telnetconsole.Listener).
+     */
+    public void activate()
+    {
+        //configure from system property
+        try
+        {
+            m_Port = Integer.parseInt( System.getProperty( "osgi.shell.telnet.port", "6666" ) );
+        }
+        catch ( NumberFormatException ex )
+        {
+            Activator.getServices().error( "Listener::activate()", ex );
+        }
+        try
+        {
+            m_MaxConnections = Integer.parseInt( System.getProperty( "osgi.shell.telnet.maxconn", "2" ) );
+        }
+        catch ( NumberFormatException ex )
+        {
+            Activator.getServices().error( "Listener::activate()", ex );
+        }
+        m_UseCounter = new AtomicInteger( 0 );
+        m_ListenerThread = new Thread( new Acceptor(), "telnetconsole.Listener" );
+        m_ListenerThread.start();
+    }//activate
+
+
+    /**
+     * Deactivates this listener.
+     * <p/>
+     * The listener's socket will be closed, which should cause an interrupt in the
+     * listener thread and allow for it to return. The calling thread joins the listener
+     * thread until it returns (to ensure a clean stop).
+     */
+    public void deactivate()
+    {
+        try
+        {
+            m_Stop = true;
+            //wait for the listener thread
+            m_ServerSocket.close();
+            m_ListenerThread.join();
+        }
+        catch ( Exception ex )
+        {
+            Activator.getServices().error( "Listener::deactivate()", ex );
+        }
+    }//deactivate
+
+    /**
+     * Class that implements the listener's accept logic as a <tt>Runnable</tt>.
+     */
+    private class Acceptor implements Runnable
+    {
+
+        /**
+         * Listens constantly to a server socket and handles incoming connections.
+         * One connection will be accepted and routed into the shell, all others will
+         * be notified and closed.
+         * <p/>
+         * The mechanism that should allow the thread to unblock from the ServerSocket.accept() call
+         * is currently closing the ServerSocket from another thread. When the stop flag is set,
+         * this should cause the thread to return and stop.
+         */
+        public void run()
+        {
+            try
+            {
+                /*
+                    A server socket is opened with a connectivity queue of a size specified
+                    in int floodProtection.  Concurrent login handling under normal circumstances
+                    should be handled properly, but denial of service attacks via massive parallel
+                    program logins should be prevented with this.
+                */
+                m_ServerSocket = new ServerSocket( m_Port, 1 );
+                do
+                {
+                    try
+                    {
+                        Socket s = m_ServerSocket.accept();
+                        if ( m_UseCounter.get() >= m_MaxConnections )
+                        {
+                            //reject with message
+                            PrintStream out = new PrintStream( s.getOutputStream() );
+                            out.print( INUSE_MESSAGE );
+                            out.flush();
+                            //close
+                            out.close();
+                            s.close();
+                        }
+                        else
+                        {
+                            m_UseCounter.increment();
+                            //run on the connection thread
+                            Thread connectionThread = new Thread( new Shell( s, m_UseCounter ) );
+                            connectionThread.start();
+                        }
+                    }
+                    catch ( SocketException ex )
+                    {
+                    }
+                }
+                while ( !m_Stop );
+
+            }
+            catch ( IOException e )
+            {
+                Activator.getServices().error( "Listener.Acceptor::activate()", e );
+            }
+        }//run
+
+    }//inner class Acceptor
+
+    private static final String INUSE_MESSAGE = "Connection refused.\r\n"
+        + "All possible connections are currently being used.\r\n";
+
+}//class Listener
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/ReentrantLock.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/ReentrantLock.java
new file mode 100644
index 0000000..874b3fc
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/ReentrantLock.java
@@ -0,0 +1,181 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+/**
+ * Implements a reentrant lock.
+ * <p/>
+ * Public domain code.
+ *
+ * @author Doug Lea
+ */
+class ReentrantLock
+{
+
+    protected Thread m_Owner = null;
+    protected long m_Holds = 0;
+
+
+    public void acquire() throws InterruptedException
+    {
+        //log.debug("acquire()::" + Thread.currentThread().toString());
+        if ( Thread.interrupted() )
+            throw new InterruptedException();
+        Thread caller = Thread.currentThread();
+        synchronized ( this )
+        {
+            if ( caller == m_Owner )
+                ++m_Holds;
+            else
+            {
+                try
+                {
+                    while ( m_Owner != null )
+                        wait();
+                    m_Owner = caller;
+                    m_Holds = 1;
+                }
+                catch ( InterruptedException ex )
+                {
+                    notify();
+                    throw ex;
+                }
+            }
+        }
+    }//acquire
+
+
+    public boolean attempt( long msecs ) throws InterruptedException
+    {
+        //log.debug("attempt()::" + Thread.currentThread().toString());
+        if ( Thread.interrupted() )
+            throw new InterruptedException();
+        Thread caller = Thread.currentThread();
+        synchronized ( this )
+        {
+            if ( caller == m_Owner )
+            {
+                ++m_Holds;
+                return true;
+            }
+            else if ( m_Owner == null )
+            {
+                m_Owner = caller;
+                m_Holds = 1;
+                return true;
+            }
+            else if ( msecs <= 0 )
+                return false;
+            else
+            {
+                long waitTime = msecs;
+                long start = System.currentTimeMillis();
+                try
+                {
+                    for ( ;; )
+                    {
+                        wait( waitTime );
+                        if ( caller == m_Owner )
+                        {
+                            ++m_Holds;
+                            return true;
+                        }
+                        else if ( m_Owner == null )
+                        {
+                            m_Owner = caller;
+                            m_Holds = 1;
+                            return true;
+                        }
+                        else
+                        {
+                            waitTime = msecs - ( System.currentTimeMillis() - start );
+                            if ( waitTime <= 0 )
+                                return false;
+                        }
+                    }
+                }
+                catch ( InterruptedException ex )
+                {
+                    notify();
+                    throw ex;
+                }
+            }
+        }
+    }//attempt
+
+
+    /**
+     * Release the lock.
+     *
+     * @throws Error thrown if not current owner of lock
+     */
+    public synchronized void release()
+    {
+        //log.debug("release()::" + Thread.currentThread().toString());
+        if ( Thread.currentThread() != m_Owner )
+            throw new Error( "Illegal Lock usage" );
+
+        if ( --m_Holds == 0 )
+        {
+            m_Owner = null;
+            notify();
+        }
+    }//release
+
+
+    /**
+     * Release the lock N times. <code>release(n)</code> is
+     * equivalent in effect to:
+     * <pre>
+     *   for (int i = 0; i < n; ++i) release();
+     * </pre>
+     * <p/>
+     *
+     * @param n times the lock should be released.
+     * @throws Error thrown if not current owner of lock
+     *               or has fewer than N holds on the lock
+     */
+    public synchronized void release( long n )
+    {
+        if ( Thread.currentThread() != m_Owner || n > m_Holds )
+            throw new Error( "Illegal Lock usage" );
+
+        m_Holds -= n;
+        if ( m_Holds == 0 )
+        {
+            m_Owner = null;
+            notify();
+        }
+    }//release
+
+
+    /**
+     * Return the number of unreleased acquires performed
+     * by the current thread.
+     * Returns zero if current thread does not hold lock.
+     *
+     * @return the number of unreleased acquires performed by the owner thread.
+     */
+    public synchronized long holds()
+    {
+        if ( Thread.currentThread() != m_Owner )
+            return 0;
+        return m_Holds;
+    }//holds
+
+}//class ReentrantLock
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/ServiceMediator.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/ServiceMediator.java
new file mode 100644
index 0000000..fa0d90a
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/ServiceMediator.java
@@ -0,0 +1,318 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+import org.apache.felix.shell.ShellService;
+import org.osgi.framework.*;
+import org.osgi.service.log.LogService;
+
+
+/**
+ * Implements a mediator pattern class for services from the OSGi container.
+ * <p/>
+ *
+ * @author Dieter Wimberger (wimpi)
+ */
+class ServiceMediator
+{
+
+    private BundleContext m_BundleContext;
+
+    private ShellService m_FelixShellService;
+    private Latch m_FelixShellServiceLatch;
+
+    private LogService m_LogService;
+    private Latch m_LogServiceLatch;
+
+
+    /**
+     * Returns a reference to the <tt>ShellService</tt> (Felix).
+     *
+     * @param wait time in milliseconds to wait for the reference if it isn't available.
+     * @return the reference to the <tt>ShellService</tt> as obtained from the OSGi service layer.
+     */
+    public ShellService getFelixShellService( long wait )
+    {
+        try
+        {
+            if ( wait < 0 )
+            {
+                m_FelixShellServiceLatch.acquire();
+            }
+            else if ( wait > 0 )
+            {
+                m_FelixShellServiceLatch.attempt( wait );
+            }
+        }
+        catch ( InterruptedException e )
+        {
+            e.printStackTrace( System.err );
+        }
+
+        return m_FelixShellService;
+    }//getFelixShellService
+
+
+    public LogService getLogServiceLatch( long wait )
+    {
+        try
+        {
+            if ( wait < 0 )
+            {
+                m_LogServiceLatch.acquire();
+            }
+            else if ( wait > 0 )
+            {
+                m_LogServiceLatch.attempt( wait );
+            }
+        }
+        catch ( InterruptedException e )
+        {
+            e.printStackTrace( System.err );
+        }
+        return m_LogService;
+    }//getLogService
+
+
+    public void info( String msg )
+    {
+        if ( m_LogService != null )
+        {
+            m_LogService.log( LogService.LOG_INFO, msg );
+        }
+        else
+        {
+            sysout( msg );
+        }
+    }//info
+
+
+    public void error( String msg, Throwable t )
+    {
+        if ( m_LogService != null )
+        {
+            m_LogService.log( LogService.LOG_ERROR, msg, t );
+        }
+        else
+        {
+            syserr( msg, t );
+        }
+    }//error
+
+
+    public void error( String msg )
+    {
+        if ( m_LogService != null )
+        {
+            m_LogService.log( LogService.LOG_ERROR, msg );
+        }
+        else
+        {
+            syserr( msg, null );
+        }
+    }//error
+
+
+    public void debug( String msg )
+    {
+        if ( m_LogService != null )
+        {
+            m_LogService.log( LogService.LOG_DEBUG, msg );
+        }
+        else
+        {
+            sysout( msg );
+        }
+    }//debug
+
+
+    public void warn( String msg )
+    {
+        if ( m_LogService != null )
+        {
+            m_LogService.log( LogService.LOG_WARNING, msg );
+        }
+        else
+        {
+            syserr( msg, null );
+        }
+    }//warn
+
+
+    private void sysout( String msg )
+    {
+        //Assemble String
+        StringBuffer sbuf = new StringBuffer();
+        Bundle b = m_BundleContext.getBundle();
+        sbuf.append( b.getHeaders().get( Constants.BUNDLE_NAME ) );
+        sbuf.append( " [" );
+        sbuf.append( b.getBundleId() );
+        sbuf.append( "] " );
+        sbuf.append( msg );
+        System.out.println( sbuf.toString() );
+    }//sysout
+
+
+    private void syserr( String msg, Throwable t )
+    {
+        //Assemble String
+        StringBuffer sbuf = new StringBuffer();
+        Bundle b = m_BundleContext.getBundle();
+        sbuf.append( b.getHeaders().get( Constants.BUNDLE_NAME ) );
+        sbuf.append( " [" );
+        sbuf.append( b.getBundleId() );
+        sbuf.append( "] " );
+        sbuf.append( msg );
+        System.err.println( sbuf.toString() );
+        if ( t != null )
+        {
+            t.printStackTrace( System.err );
+        }
+    }//logToSystem
+
+
+    /**
+     * Activates this mediator to start tracking the required services using the
+     * OSGi service layer.
+     *
+     * @param bc the bundle's context.
+     * @return true if activated successfully, false otherwise.
+     */
+    public boolean activate( BundleContext bc )
+    {
+        //get the context
+        m_BundleContext = bc;
+
+        m_FelixShellServiceLatch = createWaitLatch();
+        m_LogServiceLatch = createWaitLatch();
+
+        //prepareDefinitions listener
+        ServiceListener serviceListener = new ServiceListenerImpl();
+
+        //prepareDefinitions the filter
+        String filter = "(|(objectclass=" + ShellService.class.getName() + ")" + "(objectclass="
+            + LogService.class.getName() + "))";
+
+        try
+        {
+            //add the listener to the bundle context.
+            bc.addServiceListener( serviceListener, filter );
+
+            //ensure that already registered Service instances are registered with
+            //the manager
+            ServiceReference[] srl = bc.getServiceReferences( null, filter );
+            for ( int i = 0; srl != null && i < srl.length; i++ )
+            {
+                serviceListener.serviceChanged( new ServiceEvent( ServiceEvent.REGISTERED, srl[i] ) );
+            }
+        }
+        catch ( InvalidSyntaxException ex )
+        {
+            ex.printStackTrace( System.err );
+            return false;
+        }
+        return true;
+    }//activate
+
+
+    /**
+     * Deactivates this mediator, nulling out all references.
+     * If called when the bundle is stopped, the framework should actually take
+     * care of unregistering the <tt>ServiceListener</tt>.
+     */
+    public void deactivate()
+    {
+        m_FelixShellService = null;
+        m_FelixShellServiceLatch = null;
+        m_BundleContext = null;
+    }//deactivate
+
+
+    /**
+     * Creates a simple wait latch to be used for the mechanism that allows entities
+     * in the bundles to wait for references.
+     *
+     * @return a new Latch instance.
+     */
+    private Latch createWaitLatch()
+    {
+        return new Latch();
+    }//createWaitLatch
+
+    /**
+     * The <tt>ServiceListener</tt> implementation.
+     */
+    private class ServiceListenerImpl implements ServiceListener
+    {
+
+        public void serviceChanged( ServiceEvent ev )
+        {
+            ServiceReference sr = ev.getServiceReference();
+            Object o = null;
+            switch ( ev.getType() )
+            {
+                case ServiceEvent.REGISTERED:
+                    o = m_BundleContext.getService( sr );
+                    if ( o == null )
+                    {
+                        return;
+                    }
+                    else if ( o instanceof ShellService )
+                    {
+                        m_FelixShellService = ( ShellService ) o;
+                        m_FelixShellServiceLatch.release();
+                    }
+                    else if ( o instanceof LogService )
+                    {
+                        m_LogService = ( LogService ) o;
+                        m_LogServiceLatch.release();
+                    }
+                    else
+                    {
+                        m_BundleContext.ungetService( sr );
+                    }
+                    break;
+                case ServiceEvent.UNREGISTERING:
+                    o = m_BundleContext.getService( sr );
+                    if ( o == null )
+                    {
+                        return;
+                    }
+                    else if ( o instanceof ShellService )
+                    {
+                        m_FelixShellService = null;
+                        m_FelixShellServiceLatch = createWaitLatch();
+                    }
+                    else if ( o instanceof LogService )
+                    {
+                        m_LogService = null;
+                        m_LogServiceLatch = createWaitLatch();
+                    }
+                    else
+                    {
+                        m_BundleContext.ungetService( sr );
+                    }
+                    break;
+            }
+        }
+    }//inner class ServiceListenerImpl
+
+    public static long WAIT_UNLIMITED = -1;
+    public static long NO_WAIT = 0;
+
+}//class ServiceMediator
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/Shell.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/Shell.java
new file mode 100644
index 0000000..f7b487e
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/Shell.java
@@ -0,0 +1,131 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+import org.apache.felix.shell.ShellService;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.net.Socket;
+
+
+/**
+ * Implements the shell.
+ * <p/>
+ *
+ * @author Dieter Wimberger (wimpi)
+ */
+class Shell implements Runnable
+{
+
+    private Socket m_Socket;
+    private AtomicInteger m_UseCounter;
+
+
+    public Shell( Socket s, AtomicInteger counter )
+    {
+        m_Socket = s;
+        m_UseCounter = counter;
+    }//constructor
+
+
+    /**
+     * Runs the shell.
+     */
+    public void run()
+    {
+        try
+        {
+            PrintStream out = new TerminalPrintStream( m_Socket.getOutputStream() );
+            BufferedReader in = new BufferedReader( new TerminalReader( m_Socket.getInputStream(), out ) );
+            ReentrantLock lock = new ReentrantLock();
+
+            // Print welcome banner.
+            out.println();
+            out.println( "Felix Shell Console:" );
+            out.println( "=====================" );
+            out.println( "" );
+
+            do
+            {
+                out.print( "-> " );
+                String line = "";
+                try
+                {
+                    line = in.readLine();
+                    //make sure to capture end of stream
+                    if ( line == null )
+                    {
+                        exit();
+                        return;
+                    }
+                }
+                catch ( Exception ex )
+                {
+                    exit();
+                    return;
+                }
+
+                line = line.trim();
+                if ( line.equalsIgnoreCase( "exit" ) || line.equalsIgnoreCase( "disconnect" ) )
+                {
+                    in.close();
+                    out.close();
+                    exit();
+                    return;
+                }
+
+                ShellService shs = Activator.getServices().getFelixShellService( ServiceMediator.NO_WAIT );
+                try
+                {
+                    lock.acquire();
+                    shs.executeCommand( line, out, out );
+                }
+                catch ( Exception ex )
+                {
+                    Activator.getServices().error( "Shell::run()", ex );
+                }
+                finally
+                {
+                    lock.release();
+                }
+            }
+            while ( true );
+        }
+        catch ( IOException ex )
+        {
+            Activator.getServices().error( "Shell::run()", ex );
+        }
+    }//run
+
+
+    private void exit()
+    {
+        try
+        {
+            m_Socket.close();
+        }
+        catch ( IOException ex )
+        {
+            Activator.getServices().error( "Shell::exit()", ex );
+        }
+        m_UseCounter.decrement();
+    }//exit
+
+}//class Shell
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/TerminalPrintStream.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/TerminalPrintStream.java
new file mode 100644
index 0000000..30868e1
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/TerminalPrintStream.java
@@ -0,0 +1,78 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+
+/**
+ * Class implementing a <tt>TerminalPrintStream</tt>.
+ * <p/>
+ *
+ * @author Dieter Wimberger (wimpi)
+ */
+class TerminalPrintStream extends PrintStream
+{
+
+    /**
+     * Constructs a new instance wrapping the given <tt>OutputStream</tt>.
+     *
+     * @param tout the <tt>OutputStream</tt> to be wrapped.
+     */
+    public TerminalPrintStream( OutputStream tout )
+    {
+        super( tout );
+    }//constructor
+
+
+    public void print( String str )
+    {
+        try
+        {
+            byte[] bytes = str.getBytes();
+            out.write( bytes, 0, bytes.length );
+            flush();
+        }
+        catch ( IOException ex )
+        {
+            Activator.getServices().error( "TerminalPrintStream::print()", ex );
+        }
+    }//print
+
+
+    public void println( String str )
+    {
+        print( str + "\r\n" );
+    }//println
+
+
+    public void flush()
+    {
+        try
+        {
+            out.flush();
+        }
+        catch ( IOException ex )
+        {
+            Activator.getServices().error( "TerminalPrintStream::println()", ex );
+        }
+    }//flush
+
+}//class TerminalPrintStream
diff --git a/shell.remote/src/main/java/org/apache/felix/shell/remote/TerminalReader.java b/shell.remote/src/main/java/org/apache/felix/shell/remote/TerminalReader.java
new file mode 100644
index 0000000..afc81ca
--- /dev/null
+++ b/shell.remote/src/main/java/org/apache/felix/shell/remote/TerminalReader.java
@@ -0,0 +1,238 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*      http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.apache.felix.shell.remote;
+
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.io.Reader;
+
+
+/**
+ * Class implementing a terminal reader adapter
+ * originally designed for the BeanShell Interpreter.
+ * <p/>
+ * Provides simple line editing (Backspace, Strg-U and a history).
+ *
+ * @author Dieter Wimberger (wimpi)
+ */
+class TerminalReader extends Reader
+{
+
+    protected InputStream m_In;
+    protected PrintStream m_Out;
+    protected boolean m_Echo = false;
+    protected boolean m_EOF = false;
+
+
+    public TerminalReader( InputStream in, PrintStream out )
+    {
+        m_In = in;
+        m_Out = out;
+    }//TerminalReader
+
+
+    /**
+     * Tests if this <tt>TerminalReader</tt> will echo
+     * the character input to the terminal.
+     *
+     * @return true if echo, false otherwise.
+     */
+    public boolean isEcho()
+    {
+        return m_Echo;
+    }//isEcho
+
+
+    /**
+     * Sets if this <tt>TerminalReader</tt> will echo
+     * the character input to the terminal.
+     * <p/>
+     * This only makes sense in character input mode,
+     * in line mode the terminal will handle editing,
+     * and this is recommended for using a more complex shell.
+     * If you implement your own character based editor, you
+     * might as well change this.<br/>
+     * (Default is false).
+     *
+     * @param echo true if echo, false otherwise.
+     */
+    public void setEcho( boolean echo )
+    {
+        m_Echo = echo;
+    }//setEcho
+
+
+    public int read( char[] chars, int off, int len ) throws IOException
+    {
+        if ( m_EOF )
+        {
+            return -1;
+        }
+        for ( int i = off; i < off + len; i++ )
+        {
+            int ch = m_In.read();
+            //shortcut for EOT and simple EOF
+            if ( ch == EOT || ( i == off && ch == -1 ) )
+            {
+                return -1;
+            }
+            chars[i] = ( char ) ch;
+            if ( ch == -1 || ch == 10 || ch == 13 )
+            {
+                m_EOF = ch == -1; //store EOF
+                int read = i - off + 1;
+                if ( m_Echo )
+                {
+                    m_Out.write( CRLF );
+                }
+                return read;
+            }
+            //naive backspace handling
+            if ( ch == BS || ch == DEL )
+            {
+                if ( i > off )
+                {
+                    i = i - 2;
+                    moveLeft( 1 );
+                    eraseToEndOfLine();
+                }
+                else
+                {
+                    i--;
+                    bell();
+                }
+            }
+            else if ( ch == CTRL_U )
+            {
+                moveLeft( i - off );
+                eraseToEndOfLine();
+                i = off - 1;
+            }
+            else
+            {
+                if ( m_Echo )
+                {
+                    m_Out.write( chars[i] );
+                }
+            }
+        }
+        return len;
+    }//read
+
+
+    /**
+     * Writes the NVT BEL character to the output.
+     */
+    private void bell()
+    {
+        m_Out.write( BEL );
+        m_Out.flush();
+    }//bell
+
+
+    /**
+     * Writes the standard vt100/ansi cursor moving code to the output.
+     *
+     * @param i the number of times the cursor should be moved left.
+     * @throws IOException if I/O fails.
+     */
+    private void moveLeft( int i ) throws IOException
+    {
+        CURSOR_LEFT[2] = Byte.decode( Integer.toString( i ) ).byteValue();
+        m_Out.write( CURSOR_LEFT );
+        m_Out.flush();
+    }//moveLeft
+
+
+    /**
+     * Writes the standard vt100/ansi sequence for erasing to the end of the current line.
+     *
+     * @throws IOException if I/O fails.
+     */
+    private void eraseToEndOfLine() throws IOException
+    {
+        m_Out.write( ERASE_TEOL );
+        m_Out.flush();
+    }//eraseToEndOfLine
+
+
+    /**
+     * Closes this reader.
+     * Note: will close the input, but not the output.
+     *
+     * @throws IOException
+     */
+    public void close() throws IOException
+    {
+        m_In.close();
+    }//close
+
+    /**
+     * <b>Bell</b><br>
+     * The ANSI defined byte code for the NVT bell.
+     */
+    public static final byte BEL = 7;
+
+    /**
+     * <b>BackSpace</b><br>
+     * The ANSI defined byte code of backspace.
+     */
+    public static final byte BS = 8;
+
+    /**
+     * <b>Delete</b><br>
+     * The ANSI defined byte code of delete.
+     */
+    public static final byte DEL = 127;
+
+    /**
+     * CTRL-u
+     */
+    public static final byte CTRL_U = 21;
+
+    /**
+     * Escape character.
+     */
+    private static byte ESC = 27;
+
+    /**
+     * vt100/ansi standard sequence for moving the cursor left.
+     */
+    private static byte[] CURSOR_LEFT =
+        { ESC, '[', '1', 'D' };
+
+    /**
+     * vt100/ansi standard sequence for erasing everything from the actual cursor to
+     * the end of the current line.
+     */
+    private static byte[] ERASE_TEOL =
+        { ESC, '[', 'K' };
+
+    /**
+     * Standard NVT line break, which HAS TO BE CR and LF.
+     */
+    private static byte[] CRLF =
+        { '\r', '\n' };
+
+    /**
+     * Standard ASCII end of transmission.
+     */
+    private static byte EOT = 4;
+
+}//class TerminalReader