FileDocCategorySizeDatePackage
PlatformManagerImpl.javaAPI DocAzureus 3.0.3.421545Tue Sep 04 19:01:58 BST 2007org.gudy.azureus2.platform.macosx

PlatformManagerImpl

public class PlatformManagerImpl extends Object implements org.gudy.azureus2.platform.PlatformManager, AEDiagnosticsEvidenceGenerator
Performs platform-specific operations with Mac OS X
author
James Yeh
version
1.0 Initial Version
see
PlatformManager

Fields Summary
private static final LogIDs
LOGID
protected static PlatformManagerImpl
singleton
protected static AEMonitor
class_mon
private final HashSet
capabilitySet
Constructors Summary
public PlatformManagerImpl()
Creates a new PlatformManager and initializes its capabilities

        capabilitySet.add(PlatformManagerCapabilities.RecoverableFileDelete);
        capabilitySet.add(PlatformManagerCapabilities.ShowFileInBrowser);
        capabilitySet.add(PlatformManagerCapabilities.ShowPathInCommandLine);
        capabilitySet.add(PlatformManagerCapabilities.CreateCommandLineProcess);
        capabilitySet.add(PlatformManagerCapabilities.GetUserDataDirectory);
        capabilitySet.add(PlatformManagerCapabilities.UseNativeScripting);
        capabilitySet.add(PlatformManagerCapabilities.PlaySystemAlert);
        
        if (OSXAccess.isLoaded()) {
	        capabilitySet.add(PlatformManagerCapabilities.GetVersion);
        }
        AEDiagnostics.addEvidenceGenerator(this);
    
Methods Summary
public voidaddListener(org.gudy.azureus2.platform.PlatformManagerListener listener)

    
protected static booleancompileOSAScript(java.lang.CharSequence cmd, java.io.File destination)
Compiles a new AppleScript instance to the specified location

param
cmd Command to compile; do not surround command with extra quotation marks
param
destination Destination location of the AppleScript file
return
True if compiled successfully

        return compileOSAScript(new CharSequence[]{cmd}, destination);
    
protected static booleancompileOSAScript(java.lang.CharSequence[] cmds, java.io.File destination)
Compiles a new AppleScript instance to the specified location

param
cmds Sequence of commands to compile; do not surround command with extra quotation marks
param
destination Destination location of the AppleScript file
return
True if compiled successfully

        long start = System.currentTimeMillis();
        Debug.outNoStack("Compiling OSAScript: " + destination.getPath());
        for (int i = 0; i < cmds.length; i++)
        {
            Debug.outNoStack("\t" + cmds[i]);
        }

        String[] cmdargs = new String[2 * cmds.length + 3];
        cmdargs[0] = "osacompile";
        for (int i = 0; i < cmds.length; i++)
        {
            cmdargs[i * 2 + 1] = "-e";
            cmdargs[i * 2 + 2] = String.valueOf(cmds[i]);
        }

        cmdargs[cmdargs.length - 2] = "-o";
        cmdargs[cmdargs.length - 1] = destination.getPath();

        String errorMsg;
        try
        {
            Process osaProcess = performRuntimeExec(cmdargs);

            BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream()));
            errorMsg = reader.readLine();
            reader.close();
        }
        catch (IOException e)
        {
            Debug.outNoStack("OSACompile Execution Failed: " + e.getMessage());
            Debug.printStackTrace(e);
            return false;
        }

        Debug.outNoStack("OSACompile Error (if any): " + errorMsg);

        Debug.outNoStack(MessageFormat.format("OSACompile execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)}));

        return (errorMsg == null);
    
public voidcopyFilePermissions(java.lang.String from_file_name, java.lang.String to_file_name)

	    throw new PlatformManagerException("Unsupported capability called on platform manager");		
	
public voidcreateProcess(java.lang.String cmd, boolean inheritsHandles)
{@inheritDoc}

        try
        {
            performRuntimeExec(cmd.split(" "));
        }
        catch (Throwable e)
        {
            throw new PlatformManagerException("Failed to create process", e);
        }
    
public voiddispose()
{@inheritDoc}

        NativeInvocationBridge.sharedInstance().dispose();
    
public voidgenerate(IndentWriter writer)

			writer.println("PlatformManager: MacOSX");
			try {
				writer.indent();
				
				if (OSXAccess.isLoaded()) {
					try {
						writer.println("Version " + getVersion());
						writer.println("User Data Dir: " + getLocation(LOC_USER_DATA));
						writer.println("User Doc Dir: " + getLocation(LOC_DOCUMENTS));
					} catch (PlatformManagerException e) {
					}
				} else {
					writer.println("Not loaded");
				}
			} finally {
				writer.exdent();
			}
		
public java.lang.StringgetApplicationCommandLine()

		try{	    
			String	bundle_path = System.getProperty("user.dir") +SystemProperties.SEP+ SystemProperties.getApplicationName() + ".app";

			File osx_app_bundle = new File( bundle_path ).getAbsoluteFile();
			
			if( !osx_app_bundle.exists() ) {
				String msg = "OSX app bundle not found: [" +osx_app_bundle.toString()+ "]";
				System.out.println( msg );
				if (Logger.isEnabled())
					Logger.log(new LogEvent(LOGID, msg));		
				throw new PlatformManagerException( msg );
			}
			
			return "open -a \"" +osx_app_bundle.toString()+ "\"";
			//return osx_app_bundle.toString() +"/Contents/MacOS/JavaApplicationStub";
			
		}
		catch( Throwable t ){	
			t.printStackTrace();
			return null;
		}
	
public java.lang.StringgetAzComputerID()

		throw new PlatformManagerException(
				"Unsupported capability called on platform manager");
	
private static java.lang.StringgetFileBrowserName()

Gets the preferred file browser name

Currently supported browsers are Path Finder and Finder. If Path Finder is currently running (not just installed), then "Path Finder is returned; else, "Finder" is returned.

return
"Path Finder" if it is currently running; else "Finder"

        try
        {
            // slowwwwwwww
            if ("true".equalsIgnoreCase(performOSAScript("tell application \"System Events\" to exists process \"Path Finder\"")))
            {
                Debug.outNoStack("Path Finder is running");

                return "Path Finder";
            }
            else
            {
                return "Finder";
            }
        }
        catch (IOException e)
        {
            Debug.printStackTrace(e);
            Logger.log(new LogEvent(LOGID, e.getMessage(), e));

            return "Finder";
        }
    
public java.io.FilegetLocation(long location_id)

		switch ((int)location_id) {
			case LOC_USER_DATA:
				return new File(getUserDataDirectory());
				
			case LOC_DOCUMENTS:
				try {
					return new File(OSXAccess.getDocDir());
				} catch (Throwable e) {
					// throws UnsatisfiedLinkError if no osxaccess
					// Sometimes throws NullPointerException

					// Usually in user.home + Documents
					return new File(System.getProperty("user.home"), "Documents");
				}
				
			case LOC_MUSIC:
				
			case LOC_VIDEO:

			default:
				return( null );
		}
		
	
public intgetPlatformType()
{@inheritDoc}

        return PT_MACOSX;
    
public static org.gudy.azureus2.platform.macosx.PlatformManagerImplgetSingleton()
Gets the platform manager singleton, which was already initialized


                  
       
    
        return singleton;
    
public java.lang.StringgetUserDataDirectory()
{@inheritDoc}

see
org.gudy.azureus2.core3.util.SystemProperties#getUserPath()

    	return new File(System.getProperty("user.home")
    			+ "/Library/Application Support/" 
    			+ SystemProperties.APPLICATION_NAME).getPath()
    			+ SystemProperties.SEP;
    
public java.lang.StringgetVersion()
{@inheritDoc}

    	if (!OSXAccess.isLoaded()) {
        throw new PlatformManagerException("Unsupported capability called on platform manager");
    	}
    	
    	return OSXAccess.getVersion();
    
public booleanhasCapability(org.gudy.azureus2.platform.PlatformManagerCapabilities capability)
{@inheritDoc}

        return capabilitySet.contains(capability);
    
private static voidinitializeSingleton()
Instantiates the singleton

        initializeSingleton();
    
        try
        {
            class_mon.enter();
            singleton = new PlatformManagerImpl();
        }
        catch (Throwable e)
        {
        	Logger.log(new LogEvent(LOGID, "Failed to initialize platform manager"
					+ " for Mac OS X", e));
        }
        finally
        {
            class_mon.exit();
        }
    
public booleanisAdditionalFileTypeRegistered(java.lang.String name, java.lang.String type)

	    throw new PlatformManagerException("Unsupported capability called on platform manager");
	
public booleanisApplicationRegistered()
Not implemented; returns True

        return true;
    
protected static java.lang.StringperformOSAScript(java.lang.CharSequence cmd)
Compiles a new AppleScript instance and runs it

param
cmd AppleScript command to execute; do not surround command with extra quotation marks
return
Output of the script
throws
IOException If the script failed to execute

        return performOSAScript(new CharSequence[]{cmd});
    
protected static java.lang.StringperformOSAScript(java.lang.CharSequence[] cmds)
Compiles a new AppleScript instance and runs it

param
cmds AppleScript Sequence of commands to execute; do not surround command with extra quotation marks
return
Output of the script
throws
IOException If the script failed to execute

        long start = System.currentTimeMillis();
        Debug.outNoStack("Executing OSAScript: ");
        for (int i = 0; i < cmds.length; i++)
        {
            Debug.outNoStack("\t" + cmds[i]);
        }

        String[] cmdargs = new String[2 * cmds.length + 1];
        cmdargs[0] = "osascript";
        for (int i = 0; i < cmds.length; i++)
        {
            cmdargs[i * 2 + 1] = "-e";
            cmdargs[i * 2 + 2] = String.valueOf(cmds[i]);
        }

        Process osaProcess = performRuntimeExec(cmdargs);
        BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getInputStream()));
        String line = reader.readLine();
        reader.close();
        Debug.outNoStack("OSAScript Output: " + line);

        reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream()));
        String errorMsg = reader.readLine();
        reader.close();

        Debug.outNoStack("OSAScript Error (if any): " + errorMsg);

        Debug.outNoStack(MessageFormat.format("OSAScript execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)}));

        try {
        	osaProcess.destroy();
        } catch (Throwable t) {
        	//ignore
        }

        if (errorMsg != null)
        {
            throw new IOException(errorMsg);
        }

        return line;
    
protected static java.lang.StringperformOSAScript(java.io.File script)
Compiles a new AppleScript instance and runs it

param
script AppleScript file (.scpt) to execute
return
Output of the script
throws
IOException If the script failed to execute

        long start = System.currentTimeMillis();
        Debug.outNoStack("Executing OSAScript from file: " + script.getPath());

        Process osaProcess = performRuntimeExec(new String[]{"osascript", script.getPath()});
        BufferedReader reader = new BufferedReader(new InputStreamReader(osaProcess.getInputStream()));
        String line = reader.readLine();
        reader.close();
        Debug.outNoStack("OSAScript Output: " + line);

        reader = new BufferedReader(new InputStreamReader(osaProcess.getErrorStream()));
        String errorMsg = reader.readLine();
        reader.close();

        Debug.outNoStack("OSAScript Error (if any): " + errorMsg);

        Debug.outNoStack(MessageFormat.format("OSAScript execution ended ({0}ms)", new Object[]{String.valueOf(System.currentTimeMillis() - start)}));

        try {
        	osaProcess.destroy();
        } catch (Throwable t) {
        	//ignore
        }
        if (errorMsg != null)
        {
            throw new IOException(errorMsg);
        }

        return line;
    
public voidperformRecoverableFileDelete(java.lang.String path)
{@inheritDoc}

        File file = new File(path);
        if(!file.exists())
        {
	        	if (Logger.isEnabled())
							Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find "
									+ file.getName()));
            return;
        }

        boolean useOSA = !NativeInvocationBridge.sharedInstance().isEnabled() || !NativeInvocationBridge.sharedInstance().performRecoverableFileDelete(file);

        if(useOSA)
        {
            try
            {
                StringBuffer sb = new StringBuffer();
                sb.append("tell application \"");
                sb.append("Finder");
                sb.append("\" to move (posix file \"");
                sb.append(path);
                sb.append("\" as alias) to the trash");

                performOSAScript(sb);
            }
            catch (Throwable e)
            {
                throw new PlatformManagerException("Failed to move file", e);
            }
        }
    
protected static java.lang.ProcessperformRuntimeExec(java.lang.String[] cmdargs)

see
Runtime#exec(String[])

        try
        {
            return Runtime.getRuntime().exec(cmdargs);
        }
        catch (IOException e)
        {
            Logger.log(new LogAlert(LogAlert.UNREPEATABLE, e.getMessage(), e));
            throw e;
        }
    
public voidping(java.net.InetAddress interface_address, java.net.InetAddress target, org.gudy.azureus2.platform.PlatformManagerPingCallback callback)

	    throw new PlatformManagerException("Unsupported capability called on platform manager");		
	
public voidplaySystemAlert()
Plays the system alert (the jingle is specified by the user in System Preferences)

        try
        {
            performRuntimeExec(new String[]{"beep"});
        }
        catch (IOException e)
        {
        	if (Logger.isEnabled())
        		Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING,
						"Cannot play system alert"));
        	Logger.log(new LogEvent(LOGID, "", e));
        }
    
public voidregisterAdditionalFileType(java.lang.String name, java.lang.String description, java.lang.String type, java.lang.String content_type)

	   throw new PlatformManagerException("Unsupported capability called on platform manager");
	
public voidregisterApplication()
Not implemented; does nothing

        // handled by LaunchServices and/0r user interaction
    
public voidremoveListener(org.gudy.azureus2.platform.PlatformManagerListener listener)

    
public voidsetTCPTOSEnabled(boolean enabled)
{@inheritDoc}

        throw new PlatformManagerException("Unsupported capability called on platform manager");
    
public voidshowFile(java.lang.String path)
{@inheritDoc}

        File file = new File(path);
        if(!file.exists())
        {
        	if (Logger.isEnabled())
        		Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find "
        				+ file.getName()));
            throw new PlatformManagerException("File not found");
        }

        showInFinder(file);
    
public voidshowInFinder(java.io.File path)

Shows the given file or directory in Finder

param
path Absolute path to the file or directory

        boolean useOSA = !NativeInvocationBridge.sharedInstance().isEnabled() || !NativeInvocationBridge.sharedInstance().showInFinder(path);

        if(useOSA)
        {
            StringBuffer sb = new StringBuffer();
            sb.append("tell application \"");
            sb.append(getFileBrowserName());
            sb.append("\" to reveal (posix file \"");
            sb.append(path);
            sb.append("\" as alias)");

            try
            {
                performOSAScript(sb);
            }
            catch (IOException e)
            {
                Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, e
						.getMessage()));
            }
        }
    
public voidshowInTerminal(java.lang.String path)

Shows the given file or directory in Terminal by executing cd /absolute/path/to

param
path Absolute path to the file or directory

        showInTerminal(new File(path));
    
public voidshowInTerminal(java.io.File path)

Shows the given file or directory in Terminal by executing cd /absolute/path/to

param
path Absolute path to the file or directory

        if (path.isFile())
        {
            path = path.getParentFile();
        }

        if (path != null && path.isDirectory())
        {
            StringBuffer sb = new StringBuffer();
            sb.append("tell application \"");
            sb.append("Terminal");
            sb.append("\" to do script \"cd ");
            sb.append(path.getAbsolutePath().replaceAll(" ", "\\ "));
            sb.append("\"");

            try
            {
                performOSAScript(sb);
            }
            catch (IOException e)
            {
                Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, e
						.getMessage()));
            }
        }
        else
        {
        	if (Logger.isEnabled())
        		Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, "Cannot find "
        				+ path.getName()));
        }
    
public booleantestNativeAvailability(java.lang.String name)

	    throw new PlatformManagerException("Unsupported capability called on platform manager");		
	
public voidtraceRoute(java.net.InetAddress interface_address, java.net.InetAddress target, org.gudy.azureus2.platform.PlatformManagerPingCallback callback)

	    throw new PlatformManagerException("Unsupported capability called on platform manager");		
	
public voidunregisterAdditionalFileType(java.lang.String name, java.lang.String type)

		throw new PlatformManagerException("Unsupported capability called on platform manager");