/***********************************************************************
*
* Copyright (c) 2006 Manuel Traut and Volker Dahnke
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors: Manuel Traut and Volker Dahnke
*
************************************************************************/
package YalpOutputs.YalpVlcTelnetOutput;
import java.net.Socket;
import java.io.*;
import org.apache.commons.net.telnet.*;
/*******************************************************************************
*
* Class TelnetInterface
*
* handels telnet connection
*
* @author Volker Dahnke / Manuel Traut
*
* @version 0.1 20-11-2005
*
* @see VlcStreamer
*
******************************************************************************/
public class TelnetInterface {
private PrintStream out;
private InputStream in;
private TelnetClient tc = new TelnetClient();
/**
* creates socket, logs on
*
* @param host
* hostname of telnetserver
* @param port
* destination port
* @param pass
* password
*
*/
public TelnetInterface(String host, int port, String pass){
try{
this.tc.connect(host,port);
this.out = new PrintStream(this.tc.getOutputStream());
this.in = this.tc.getInputStream();
} catch(IOException e){
System.out.println("server.TelnetInterface.java: Telnet connection "+host+":"+port+" failed");
return;
}
readUntil( "Password:" );
write(pass);
// Advance to a prompt
readUntil("> ");
}
/**
* write to TelnetInterface
* @param value
* String to write to Interface
*/
public void write( String value ) {
try {
out.println( value );
out.flush();
System.out.println( value );
}
catch( Exception e ) {
e.printStackTrace();
}
}
/**
* reads output of telnet client
* @param pattern
* for stop reading
* @return String
*/
public String readUntil( String pattern ) {
try {
char lastChar = pattern.charAt( pattern.length() - 1 );
StringBuffer sb = new StringBuffer();
char ch = ( char )in.read();
while( true ) {
System.out.print( ch );
sb.append( ch );
if( ch == lastChar ) {
if( sb.toString().endsWith( pattern ) ) {
return sb.toString();
}
}
ch = ( char )in.read();
}
}
catch( Exception e ) {
e.printStackTrace();
}
return null;
}
/**
* executes command
* @param cmd
* any telnet command
* @return String
* telnet output caused by the command
* null if failed
*/
public String exec(String cmd){
try {
write(cmd);
return readUntil( "> " );
}
catch( Exception e ) {
e.printStackTrace();
}
return null;
}
/**
* close telnet connection
*
* @return boolean
* true: connection closed
* false: connection close failed
*/
public boolean close(){
try {
this.tc.disconnect();
} catch(IOException e){
return false;
}
return true;
}
}