001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.xbean.terminal.telnet;
018
019import java.io.IOException;
020import java.io.InputStream;
021import java.io.OutputStream;
022import java.io.PrintStream;
023import java.net.Socket;
024
025import org.apache.xbean.command.CommandShell;
026
027public class TelnetShell {
028
029    private final String serverName;
030
031    public TelnetShell(String serverName) {
032        this.serverName = serverName;
033    }
034
035    public void service(Socket socket) throws IOException {
036
037        try {
038            service(socket.getInputStream(), socket.getOutputStream());
039        } catch (IOException e) {
040            e.printStackTrace();
041        } finally {
042            if (socket != null) socket.close();
043        }
044    }
045
046    public void service(InputStream in, OutputStream out) throws IOException {
047        InputStream telnetIn = null;
048        PrintStream telnetOut = null;
049        try {
050            telnetIn = new TelnetInputStream(in, out);
051            telnetOut = new TelnetPrintStream(out);
052
053            telnetOut.println(serverName + " Console");
054            telnetOut.println("type \'help\' for a list of commands");
055
056            // TODO:1: Login
057            //...need a security service first
058
059            CommandShell shell = new CommandShell(serverName);
060            shell.main(new String[]{}, telnetIn, telnetOut);
061
062        } catch (Throwable t) {
063            // TODO: log this
064        } finally {
065            if (telnetIn != null){
066                telnetIn.close();
067            }
068            if (telnetOut != null) {
069                telnetOut.close();
070            }
071        }
072    }
073}