FileDocCategorySizeDatePackage
ConsoleInput.javaAPI DocAzureus 3.0.3.421409Fri Dec 22 00:42:24 GMT 2006org.gudy.azureus2.ui.console

ConsoleInput

public class ConsoleInput extends Thread
author
Tobias Minich

Fields Summary
private static final String
ALIASES_CONFIG_FILE
public final com.aelitis.azureus.core.AzureusCore
azureus_core
public final PrintStream
out
public final List
torrents
public File[]
adds
private final CommandReader
br
private final boolean
controlling
private boolean
running
private final Vector
oldcommand
private static final List
pluginCommands
public final Properties
aliases
private final Map
commands
private final List
helpItems
private final UserProfile
userProfile
Constructors Summary
public ConsoleInput(String con, com.aelitis.azureus.core.AzureusCore _azureus_core, InputStream _in, PrintStream _out, Boolean _controlling)

		this(con, _azureus_core, new InputStreamReader(_in), _out, _controlling);
	
public ConsoleInput(String con, com.aelitis.azureus.core.AzureusCore _azureus_core, Reader _in, PrintStream _out, Boolean _controlling)
Creates a new instance of ConsoleInput

		this( con, _azureus_core, _in, _out, _controlling, UserProfile.DEFAULT_USER_PROFILE);
	
public ConsoleInput(String con, com.aelitis.azureus.core.AzureusCore _azureus_core, Reader _in, PrintStream _out, Boolean _controlling, UserProfile profile)

		super("Console Input: " + con);
		this.out = _out;
		this.azureus_core	= _azureus_core;
		this.userProfile 	= profile;
		this.controlling = _controlling.booleanValue();
		this.br = new CommandReader(_in);
		
		
		System.out.println( "ConsoleInput: initializing..." );
		initialise();
		System.out.println( "ConsoleInput: initialized OK" );
		
		System.out.println( "ConsoleInput: starting..." );
		start();
		System.out.println( "ConsoleInput: started OK" );
	
public ConsoleInput(com.aelitis.azureus.core.AzureusCore _azureus_core, PrintStream _out)
Simple constructor to allow other components to use the console commands such as "set"

param
con
param
_azureus_core
param
_out

		super( "" );
		this.out = _out;
		this.azureus_core	= _azureus_core;
		this.userProfile 	= UserProfile.DEFAULT_USER_PROFILE;
		this.controlling 	= false;
		this.br 			= new CommandReader( new InputStreamReader( new ByteArrayInputStream(new byte[0])));
				
		if (Logger.getRootLogger().getAppender("ConsoleAppender")==null) {
	      Appender app;
	      app = new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN));
	      app.setName("ConsoleAppender");
	      app.addFilter( new DenyAllFilter() );  //'log off' by default
	      Logger.getRootLogger().addAppender(app);
	    }
		
		initialise();
	
Methods Summary
public voiddownloadRemoteTorrent(java.lang.String url)
downloads the remote torrent file. once we have downloaded the .torrent file, we pass the data to the downloadTorrent() method for further processing

		downloadRemoteTorrent(url, getDefaultSaveDirectory());
	
public voiddownloadRemoteTorrent(java.lang.String url, java.lang.String outputDir)
downloads the remote torrent file. once we have downloaded the .torrent file, we pass the data to the downloadTorrent() method for further processing

param
url
param
outputDir

		TorrentDownloader downloader = TorrentDownloaderFactory.create(new TorrentDownloaderCallBackInterface() {
			public void TorrentDownloaderEvent(int state, TorrentDownloader inf) {
				if( state == TorrentDownloader.STATE_FINISHED )
				{
					out.println("torrent file download complete. starting torrent");
					TorrentDownloaderManager.getInstance().remove(inf);
					downloadTorrent( inf.getFile().getAbsolutePath(), outputDir );
				}
				else
					TorrentDownloaderManager.getInstance().TorrentDownloaderEvent(state, inf);
			}
		}, url, null, null, true);
		TorrentDownloaderManager.getInstance().add(downloader);
	
public voiddownloadTorrent(java.lang.String filename, java.lang.String outputDir)
begins the download of the torrent in the specified file, downloading it to the specified output directory. We also annotate the download with the current username

param
filename
param
outputDir

		DownloadManager manager = azureus_core.getGlobalManager().addDownloadManager(filename, outputDir);
		manager.getDownloadState().setAttribute(DownloadManagerState.AT_USER, getUserProfile().getUsername());
	
public voiddownloadTorrent(java.lang.String fileName)
downloads a torrent on the local file system to the default save directory

param
fileName

		downloadTorrent(fileName, getDefaultSaveDirectory());
	
private java.io.FilegetAliasesFile()

		PluginInterface pi = azureus_core.getPluginManager().getDefaultPluginInterface();
		String azureusUserDir = pi.getUtilities().getAzureusUserDir();
		return new File(azureusUserDir, ALIASES_CONFIG_FILE);
	
public com.aelitis.azureus.core.AzureusCoregetCore()

		return( azureus_core );
	
public java.lang.StringgetDefaultSaveDirectory()
returns the default directory that torrents should be saved to unless otherwise specified

return

		try {
			String saveDir = getUserProfile().getDefaultSaveDirectory();
			if( saveDir == null )
			{
				saveDir = COConfigurationManager.getDirectoryParameter("Default save path");
				if( saveDir == null || saveDir.length() == 0 )
					saveDir = ".";
			}
			return saveDir;
		} catch (Exception e) 
		{
			e.printStackTrace();
			return ".";
		}
	
public org.gudy.azureus2.core3.global.GlobalManagergetGlobalManager()

		return( azureus_core.getGlobalManager());
	
public UserProfilegetUserProfile()

return
Returns the userProfile.

		return userProfile;
	
protected voidinitialise()

		registerAlertHandler();
		registerCommands();
		registerPluginCommands();
		registerUpdateChecker();
		try {
			loadAliases();
		} catch (IOException e) {
			out.println("Error while loading aliases: " + e.getMessage());
		}
		// populate the old command so that '.' does something sensible first time around
		oldcommand.add("sh");
		oldcommand.add("t");
	
public booleaninvokeCommand(java.lang.String command, java.util.List cargs)

		if( command.startsWith("\\") )
			command = command.substring(1);
		else if( aliases.containsKey(command) )
		{
			List list = br.parseCommandLine(aliases.getProperty(command));
			String newCommand = list.remove(0).toString().toLowerCase();
			list.addAll( cargs );
			return invokeCommand(newCommand, list);
		}
		if (commands.containsKey(command)) {
			IConsoleCommand cmd = (IConsoleCommand) commands.get(command);
			try {
				if( cargs == null )
					cargs = new ArrayList();
				cmd.execute(command, this, cargs);
				return true;
			} catch (Exception e)
			{
				out.println("> Invoking Command '"+command+"' failed. Exception: "+ Debug.getNestedExceptionMessage(e));
				return false;
			}
		} else
			return false;
	
private voidloadAliases()
read in the aliases from the alias properties file

throws
IOException

		File aliasesFile = getAliasesFile();
		out.println("Attempting to load aliases from: " + aliasesFile.getCanonicalPath());
		if ( aliasesFile.exists() )
		{
			FileInputStream fr = new FileInputStream(aliasesFile);
			aliases.clear();
			try {
				aliases.load(fr);
			} finally {
				fr.close();
			}
		}
	
public voidprintconsolehelp()

		printconsolehelp(out);
	
private voidprintconsolehelp(java.io.PrintStream os)

		os.println("> -----");
		os.println("Available console commands:");
		os.println("Command\t\t\t\tShort\tDescription");
		os.println(".\t\t\t\t\tRepeats last command (Initially 'show torrents').");
		
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		
		for (Iterator iter = helpItems.iterator(); iter.hasNext();) {
			IConsoleCommand cmd = (IConsoleCommand) iter.next();
			String cmddesc = cmd.getCommandDescriptions();
			if( cmddesc != null )
				os.println(cmddesc);
			String extraHelp = cmd.getHelpExtra();
			if( extraHelp != null )
			{
				pw.println();
				pw.println(extraHelp);
			}
		}
		os.println(sw.toString());
		os.println("> -----");
	
private static voidquit(boolean finish)

		if (finish)
			UIConst.shutdown();
	
protected voidregisterAlertHandler()

		org.gudy.azureus2.core3.logging.Logger.addListener(new ILogAlertListener() {
			private java.util.Set	history = Collections.synchronizedSet( new HashSet());
			
			public void alertRaised(LogAlert alert) {
				if (!alert.repeatable) {
					if ( history.contains( alert.text )){
						
						return;
					}
					
					history.add( alert.text );
				}
				out.println( alert.text );
				if (alert.err != null)
					alert.err.printStackTrace( out );
			}
		});
	
protected voidregisterCommand(IConsoleCommand command)

param
set

		for (Iterator iter = command.getCommandNames().iterator(); iter.hasNext();) {
			String cmdName = (String) iter.next();
			commands.put( cmdName, command);
		}
		helpItems.add(command);
	
protected voidregisterCommands()
registers the commands available to be executed from this console

		registerCommand(new XML());
		registerCommand(new Hack());
		registerCommand(new AddFind());
		registerCommand(new TorrentCheck());
		registerCommand(new TorrentQueue());
		registerCommand(new TorrentRemove());
		registerCommand(new TorrentStart());
		registerCommand(new TorrentStop());
		registerCommand(new TorrentHost());
		registerCommand(new TorrentPublish());
		registerCommand(new TorrentForceStart());
		registerCommand(new TorrentLog());
		registerCommand(new Log());
		registerCommand(new Move());
		registerCommand(new Share());
		registerCommand(new Set());
		registerCommand(new Show());
		registerCommand(new CommandUI());
		registerCommand(new CommandLogout());
		registerCommand(new CommandQuit());
		registerCommand(new CommandHelp());
		registerCommand(new Alias());
		registerCommand(new Priority());
	
public static voidregisterPluginCommand(java.lang.Class clazz)
can be used by plugins to register console commands since they may not have access o each ConsoleInput object that is created.

	
	                      	 
	    
	
		if( ! clazz.isInstance(IConsoleCommand.class) )
		{
			throw new IllegalArgumentException("Class must be extend IConsoleCommand");
		}
		pluginCommands.add( clazz );
	
private voidregisterPluginCommands()
instantiates each of the plugin commands and registers t

		Class clazz;
		for (Iterator iter = pluginCommands.iterator(); iter.hasNext();) {
			clazz = (Class) iter.next();
			try {
				IConsoleCommand command = (IConsoleCommand) clazz.newInstance();
				registerCommand(command);
			} catch (InstantiationException e)
			{
				out.println("Error while registering plugin command: " + clazz.getName() + ":" + e.getMessage());
			} catch (IllegalAccessException e) {
				out.println("Error while registering plugin command: " + clazz.getName() + ":" + e.getMessage());
			}
		}
	
protected voidregisterUpdateChecker()

		boolean check_at_start	= COConfigurationManager.getBooleanParameter( "update.start", true );

		if ( !check_at_start ){
			
			return;
		}
		
			// we've got to disable the auto-update components as we're not using them (yet...)
		
		PluginManager	pm = azureus_core.getPluginManager();
		
		pm.getPluginInstaller().addListener(
			new PluginInstallerListener()
			{
				public boolean
				installRequest(
					String				reason,
					InstallablePlugin	plugin )
				
					throws PluginException
					{
						out.println( "Plugin installation request for '" + plugin.getName() + "' - " + reason );
							
						String	desc = plugin.getDescription();
						
						String[]	bits = desc.split( "\n" );
						
						for (int i=0;i<bits.length;i++){
							
							out.println( "\t" + bits[i]);
						}
						
						return( true );
					}
			});
		
		PluginInterface	pi = pm.getPluginInterfaceByClass( CorePatchChecker.class );
		
		if ( pi != null ){
			
			pi.setDisabled( true );
		}
		
		pi = pm.getPluginInterfaceByClass( UpdaterUpdateChecker.class );
		
		if ( pi != null ){
			
			pi.setDisabled( true );
		}
		
		UpdateManager update_manager = azureus_core.getPluginManager().getDefaultPluginInterface().getUpdateManager();
		
		UpdateCheckInstance	checker = update_manager.createUpdateCheckInstance();
		
		checker.addListener(
			new UpdateCheckInstanceListener()
			{
				public void
				cancelled(
					UpdateCheckInstance		instance )
				{
					
				}
				
				public void
				complete(
					UpdateCheckInstance		instance )
				{
					Update[] 	updates = instance.getUpdates();
					
					for (int i=0;i<updates.length;i++){
						
						Update	update = updates[i];
												
						out.println( "Update available for '" + update.getName() + "', new version = " + update.getNewVersion());
												
						String[]	descs = update.getDescription();
						
						for (int j=0;j<descs.length;j++){
							
							out.println( "\t" + descs[j] );
						}
					}
				}
			});
		
		checker.start();
		
	
public voidrun()

		List comargs;
		running = true;
		while (running) {
			try {
				String line = br.readLine();
				comargs = br.parseCommandLine(line);
			} catch (Exception e) {
				out.println("Stopping console input reader because of exception: " + e.getMessage());
				running = false;
				break;
			}
			if (!comargs.isEmpty()) {
				String command = ((String) comargs.get(0)).toLowerCase();
				if( ".".equals(command) )
				{
					if (oldcommand != null) {
						comargs.clear();
						comargs.addAll(oldcommand);
						command = ((String) comargs.get(0)).toLowerCase();
					} else {
						out.println("No old command. Remove commands are not repeated to prevent errors");
					}
				}
				oldcommand.clear();
				oldcommand.addAll(comargs);
				comargs.remove(0);
				
				try {
					if (!invokeCommand(command, comargs)) {
						out.println("> Command '" + command + "' unknown (or . used without prior command)");
					}
				} catch (Throwable e)
				{
					out.println("Exception occurred when executing command: '" + command + "'");
					e.printStackTrace(out);
				}
			}
		}
	
public voidsaveAliases()
writes the aliases back out to the alias file

		File aliasesFile = getAliasesFile();
		try {
			out.println("Saving aliases to: " + aliasesFile.getCanonicalPath());
			FileOutputStream fo = new FileOutputStream(aliasesFile);
			aliases.store(fo, "This aliases file was automatically written by Azureus");
		} catch (IOException e) {
			out.println("> Error saving aliases to " + aliasesFile.getPath() + ":" + e.getMessage());
		}
	
protected voidunregisterCommand(IConsoleCommand command)

		for (Iterator iter = command.getCommandNames().iterator(); iter.hasNext();) {
			String cmdName = (String) iter.next();
			if( command.equals(commands.get(cmdName)) )
				commands.remove( cmdName );
		}
		helpItems.remove(command);
	
protected voidunregisterCommand(java.lang.String commandName)

		IConsoleCommand cmd = (IConsoleCommand)commands.get(commandName);
		if( cmd == null )
			return;
		// check if there are any more commands registered to this command object,
		// otherwise remove it
		int numCommands = 0;
		for (Iterator iter = commands.entrySet().iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			if( cmd.equals(entry.getValue()) )
				numCommands++;
		}
		if( numCommands == 1)
			unregisterCommand(cmd);
		else
			commands.remove(commandName);
	
public static voidunregisterPluginCommand(java.lang.Class clazz)

		pluginCommands.remove(clazz);