Package com.adito.agent.client.util

Source Code of com.adito.agent.client.util.BrowserLauncher

package com.adito.agent.client.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Vector;

/**
* BrowserLauncher is a class that provides one static method, openURL, which
* opens the default web browser for the current user of the system to the given
* URL. It may support other protocols depending on the system -- mailto, ftp,
* etc. -- but that has not been rigorously tested and is not guaranteed to
* work.
* <p>
* Yes, this is platform-specific code, and yes, it may rely on classes on
* certain platforms that are not part of the standard JDK. What we're trying to
* do, though, is to take something that's frequently desirable but inherently
* platform-specific -- opening a default browser -- and allow programmers (you,
* for example) to do so without worrying about dropping into native code or
* doing anything else similarly evil.
* <p>
* Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
* systems without modification or a need for additional libraries. All classes
* that are required on certain platforms to allow this to run are dynamically
* loaded at runtime via reflection and, if not found, will not cause this to do
* anything other than returning an error when opening the browser.
* <p>
* There are certain system requirements for this class, as it's running through
* Runtime.exec(), which is Java's way of making a native system call.
* Currently, this requires that a Macintosh have a Finder which supports the
* GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
* Internet Scripting AppleScript dictionary installed in the Scripting
* Additions folder in the Extensions folder (which is installed by default as
* far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
* systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
* 4.0, as well as later versions of all). On other systems, this drops back
* from the inherently platform-sensitive concept of a default browser and
* simply attempts to launch Netscape via a shell command.
* <p>
* This code is Copyright 1999-2002 by Eric Albert (ejalbert@cs.stanford.edu)
* and may be redistributed or modified in any form without restrictions as long
* as the portion of this comment from this paragraph through the end of the
* comment is not removed. The author requests that he be notified of any
* application, applet, or other binary that makes use of this code, but that's
* more out of curiosity than anything and is not required. This software
* includes no warranty. The author is not repsonsible for any loss of data or
* functionality or any adverse or unexpected effects of using this software.
* <p>
* Credits: <br>
* Steven Spencer, JavaWorld magazine ( <a
* href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip
* 66 </a>) <br>
* Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
* Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, Ron Rabakukk, and
* Glenn Vanderburg
*
* @author Eric Albert ( <a
*         href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu </a>)
*
* <p>
* Additional
* <p>
* <p>
* Changes made by Brett Smith ( <a href="mailto:brett@localhost">brett@localhost.
* </a> to allow a command to be specified that will always be used. Copyright
* 2004 3SP <a href="http://localhost">3SP </a>.
*/
public class BrowserLauncher {

  /**
   * The Java virtual machine that we are running on. Actually, in most cases we
   * only care about the operating system, but some operating systems require us
   * to switch on the VM.
   */
  private static int jvm;

  /** The browser for the system */
  private static Object browser;

  /** Browser command to always use */
  private static String browserCommand;

  /**
   * Caches whether any classes, methods, and fields that are not part of the
   * JDK and need to be dynamically loaded at runtime loaded successfully.
   * <p>
   * Note that if this is <code>false</code>,<code>openURL()</code> will
   * always return an IOException.
   */
  private static boolean loadedWithoutErrors;

  /** The com.apple.mrj.MRJFileUtils class */
  private static Class mrjFileUtilsClass;

  /** The com.apple.mrj.MRJOSType class */
  private static Class mrjOSTypeClass;

  /** The com.apple.MacOS.AEDesc class */
  private static Class aeDescClass;

  /** The <init>(int) method of com.apple.MacOS.AETarget */
  private static Constructor aeTargetConstructor;

  /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
  private static Constructor appleEventConstructor;

  /** The <init>(String) method of com.apple.MacOS.AEDesc */
  private static Constructor aeDescConstructor;

  /** The findFolder method of com.apple.mrj.MRJFileUtils */
  private static Method findFolder;

  /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
  private static Method getFileCreator;

  /** The getFileType method of com.apple.mrj.MRJFileUtils */
  private static Method getFileType;

  /** The openURL method of com.apple.mrj.MRJFileUtils */
  private static Method openURL;

  /** The makeOSType method of com.apple.MacOS.OSUtils */
  private static Method makeOSType;

  /** The putParameter method of com.apple.MacOS.AppleEvent */
  private static Method putParameter;

  /** The sendNoReply method of com.apple.MacOS.AppleEvent */
  private static Method sendNoReply;

  /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
  private static Object kSystemFolderType;

  /** The keyDirectObject AppleEvent parameter type */
  private static Integer keyDirectObject;

  /** The kAutoGenerateReturnID AppleEvent code */
  private static Integer kAutoGenerateReturnID;

  /** The kAnyTransactionID AppleEvent code */
  private static Integer kAnyTransactionID;

  /** The linkage object required for JDirect 3 on Mac OS X */
  private static Object linkage;

  /** The framework to reference on Mac OS X 10.0.x */
  private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox"; //$NON-NLS-1$

  /** JVM constant for MRJ 2.0 */
  private static final int MRJ_2_0 = 0;

  /** JVM constant for MRJ 2.1.x and 2.2.x */
  private static final int MRJ_2_1 = 1;

  /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
  private static final int MRJ_3_0 = 3;

  /** JVM constant for Java 1.3.x on Mac OS X 10.1 and later (MRJ 3.1 and 3.2) */
  private static final int MRJ_3_1 = 4;

  /** JVM constant for Java 1.4.x and later on Mac OS X */
  private static final int MRJ_COCOA = 5;

  /** JVM constant for any Windows NT JVM */
  private static final int WINDOWS_NT = 6;

  /** JVM constant for any Windows 9x JVM */
  private static final int WINDOWS_9x = 7;

  /** JVM constant for any other platform */
  private static final int OTHER = -1;

  /**
   * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
   * non-U.S. English systems from working properly.
   */
  private static final String FINDER_TYPE = "FNDR"; //$NON-NLS-1$

  /**
   * The creator code of the Finder on a Macintosh, which is needed to send
   * AppleEvents to the application.
   */
  private static final String FINDER_CREATOR = "MACS"; //$NON-NLS-1$

  /** The name for the AppleEvent type corresponding to a GetURL event. */
  private static final String GURL_EVENT = "GURL"; //$NON-NLS-1$

  /**
   * The first parameter that needs to be passed into Runtime.exec() to open the
   * default web browser on Windows.
   */
  private static final String FIRST_WINDOWS_PARAMETER = "/c"; //$NON-NLS-1$

  /** The second parameter for Runtime.exec() on Windows. */
  private static final String SECOND_WINDOWS_PARAMETER = "start"; //$NON-NLS-1$

  /**
   * The third parameter for Runtime.exec() on Windows. This is a "title"
   * parameter that the command line expects. Setting this parameter allows URLs
   * containing spaces to work.
   */
  private static final String THIRD_WINDOWS_PARAMETER = "\"\""; //$NON-NLS-1$

  /**
   * The shell parameters for Netscape that opens a given URL in an already-open
   * copy of Netscape on many command-line systems.
   */
  private static final String NETSCAPE_REMOTE_PARAMETER = "-remote"; //$NON-NLS-1$
  private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL("; //$NON-NLS-1$
  private static final String NETSCAPE_OPEN_PARAMETER_END = ")'"; //$NON-NLS-1$

  /**
   * The message from any exception thrown throughout the initialization
   * process.
   */
  private static String errorMessage;

  /**
   * An initialization block that determines the operating system and loads the
   * necessary runtime data.
   */
  static {
    loadedWithoutErrors = true;
    String osName = System.getProperty("os.name"); //$NON-NLS-1$
    if (osName.startsWith("Mac OS")) { //$NON-NLS-1$
      String javaVersion = System.getProperty("java.version"); //$NON-NLS-1$
      String majorJavaVersion = javaVersion.substring(0, 3);
      try {
        double version = Double.valueOf(majorJavaVersion).doubleValue();
        if (version >= 1.4) {
          jvm = MRJ_COCOA;
        }
      } catch (NumberFormatException nfe) {
        // Fall through to earlier versions of Java on the Mac.
      }
      if (jvm != MRJ_COCOA) {
        String mrjVersion = System.getProperty("mrj.version"); //$NON-NLS-1$
        String majorMRJVersion = mrjVersion.substring(0, 3);
        try {
          double version = Double.valueOf(majorMRJVersion).doubleValue();
          if (version == 2) {
            jvm = MRJ_2_0;
          } else if (version >= 2.1 && version < 3) {
            // Assume that all post-2.1 2.x versions of MRJ work the same. MRJ
            // 2.1 actually
            // works via Runtime.exec() and 2.2 supports that but has an
            // openURL() method
            // as well that we don't use because the Runtime.exec() method works
            // fine.
            jvm = MRJ_2_1;
          } else if (version == 3.0) {
            jvm = MRJ_3_0;
          } else if (version >= 3.1) {
            // Assume that all 3.1 and later versions of MRJ work the same.
            jvm = MRJ_3_1;
          } else {
            loadedWithoutErrors = false;
            errorMessage = "Unsupported MRJ version: " + version; //$NON-NLS-1$
          }
        } catch (NumberFormatException nfe) {
          loadedWithoutErrors = false;
          errorMessage = "Invalid MRJ version: " + mrjVersion; //$NON-NLS-1$
        }
      }
    } else if (osName.startsWith("Windows")) { //$NON-NLS-1$
      if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
        jvm = WINDOWS_9x;
      } else {
        jvm = WINDOWS_NT;
      }
    } else {
      jvm = OTHER;
    }

    if (loadedWithoutErrors) { // if we haven't hit any errors yet
      loadedWithoutErrors = loadClasses();
    }
  }

  /**
   * This class should be never be instantiated; this just ensures so.
   */
  private BrowserLauncher() {
  }

  /**
   * Manually set the browser command. If this is set then none the this command
   * will <b>always </b> be used.
   *
   * @param browserCommand
   *          browser command
   */
  public static void setBrowserCommand(String browserCommand) {
    BrowserLauncher.browserCommand = browserCommand;
  }

  /**
   * Split a string into an array taking into account delimiters, quotes
   * and escapes
   *
   * @param str string to split
   * @param delim delimiter
   * @param quote quote character
   * @param escape escape character
   * @return array
   */

  public static String[] splitString(String str, char delim, char quote, char escape) {
    Vector v = new Vector();
    StringBuffer str1 = new StringBuffer();
    char ch = ' ';
    boolean inQuote = false;
    boolean escaped = false;

    for (int i = 0; i < str.length(); i++) {
      ch = str.charAt(i);

      if ((escape != -1) && (ch == escape) && !escaped) {
        escaped = true;
      } else {
        if ((quote != -1) && (ch == quote) && !escaped) {
          inQuote = !inQuote;
        } else if (!inQuote && (ch == delim && !escaped)) {
          v.addElement(str1.toString());
          str1.setLength(0);
        } else {
          str1.append(ch);
        }
        if (escaped) {
          escaped = false;
        }
      }
    }

    if (str.length() > 0) {
      v.addElement(str1.toString());

    }
    String[] array;
    array = new String[v.size()];
    v.copyInto(array);

    return array;
  }

  /**
   * Called by a static initializer to load any classes, fields, and methods
   * required at runtime to locate the user's web browser.
   *
   * @return <code>true</code> if all intialization succeeded
   *         <code>false</code> if any portion of the initialization failed
   */
  private static boolean loadClasses() {
    switch (jvm) {
      case MRJ_2_0 :
        return loadMRJ20Classes();
      case MRJ_2_1 :
        try {
          mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils"); //$NON-NLS-1$
          mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType"); //$NON-NLS-1$
          Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType"); //$NON-NLS-1$
          kSystemFolderType = systemFolderField.get(null);
          findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[]{mrjOSTypeClass}); //$NON-NLS-1$
          getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[]{File.class}); //$NON-NLS-1$
          getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[]{File.class}); //$NON-NLS-1$
        } catch (ClassNotFoundException cnfe) {
          errorMessage = cnfe.getMessage();
          return false;
        } catch (NoSuchFieldException nsfe) {
          errorMessage = nsfe.getMessage();
          return false;
        } catch (NoSuchMethodException nsme) {
          errorMessage = nsme.getMessage();
          return false;
        } catch (SecurityException se) {
          errorMessage = se.getMessage();
          return false;
        } catch (IllegalAccessException iae) {
          errorMessage = iae.getMessage();
          return false;
        }
        break;
      case MRJ_3_0 :
        try {
          Class linker = Class.forName("com.apple.mrj.jdirect.Linker"); //$NON-NLS-1$
          Constructor constructor = linker.getConstructor(new Class[]{Class.class});
          linkage = constructor.newInstance(new Object[]{BrowserLauncher.class});
        } catch (ClassNotFoundException cnfe) {
          errorMessage = cnfe.getMessage();
          return false;
        } catch (NoSuchMethodException nsme) {
          errorMessage = nsme.getMessage();
          return false;
        } catch (InvocationTargetException ite) {
          errorMessage = ite.getMessage();
          return false;
        } catch (InstantiationException ie) {
          errorMessage = ie.getMessage();
          return false;
        } catch (IllegalAccessException iae) {
          errorMessage = iae.getMessage();
          return false;
        }
        break;
      case MRJ_3_1 :
      case MRJ_COCOA :
        String className;
        if (jvm == MRJ_3_1) {
          className = "com.apple.mrj.MRJFileUtils"; //$NON-NLS-1$
        } else {
          className = "com.apple.eio.FileManager"; //$NON-NLS-1$
        }
        try {
          mrjFileUtilsClass = Class.forName(className);
          openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[]{String.class}); //$NON-NLS-1$
        } catch (ClassNotFoundException cnfe) {
          errorMessage = cnfe.getMessage();
          return false;
        } catch (NoSuchMethodException nsme) {
          errorMessage = nsme.getMessage();
          return false;
        }
        break;
      default :
        break;
    }
    return true;
  }

  /**
   * Loads the classes, fields, and methods needed when running under MRJ 2.0.
   * Sets <code>errorMessage</code> if it fails.
   *
   * @return <code>true</code> if all operations succeeded; <code>false</code>
   *         otherwise
   */
  private static boolean loadMRJ20Classes() {
    try {
      Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget"); //$NON-NLS-1$
      Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils"); //$NON-NLS-1$
      Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent"); //$NON-NLS-1$
      Class aeClass = Class.forName("com.apple.MacOS.ae"); //$NON-NLS-1$
      aeDescClass = Class.forName("com.apple.MacOS.AEDesc"); //$NON-NLS-1$

      aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[]{int.class});
      appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[]{int.class, int.class, aeTargetClass, int.class,
          int.class});
      aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[]{String.class});

      makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class[]{String.class}); //$NON-NLS-1$
      putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[]{int.class, aeDescClass}); //$NON-NLS-1$
      sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[]{}); //$NON-NLS-1$

      Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject"); //$NON-NLS-1$
      keyDirectObject = (Integer) keyDirectObjectField.get(null);
      Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID"); //$NON-NLS-1$
      kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
      Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID"); //$NON-NLS-1$
      kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
    } catch (ClassNotFoundException cnfe) {
      errorMessage = cnfe.getMessage();
      return false;
    } catch (NoSuchMethodException nsme) {
      errorMessage = nsme.getMessage();
      return false;
    } catch (NoSuchFieldException nsfe) {
      errorMessage = nsfe.getMessage();
      return false;
    } catch (IllegalAccessException iae) {
      errorMessage = iae.getMessage();
      return false;
    }
    return true;
  }

  /**
   * Attempts to locate the default web browser on the local system. Caches the
   * result so it only locates the browser once for each use of this class per
   * JVM instance.
   *
   * @return The browser for the system. Note that this may not be what you
   *         would consider to be a standard web browser; instead, it's the
   *         application that gets called to open the default web browser. In
   *         some cases this will be a non-String object that provides the means
   *         of calling the default browser.
   */
  private static Object locateBrowser() {
    if (browser != null) {
      return browser;
    }
    switch (jvm) {
      case MRJ_2_0 :
        try {
          Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[]{FINDER_CREATOR});
          Object aeTarget = aeTargetConstructor.newInstance(new Object[]{finderCreatorCode});
          Integer gurlType = (Integer) makeOSType.invoke(null, new Object[]{GURL_EVENT});
          Object appleEvent = appleEventConstructor.newInstance(new Object[]{gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
              kAnyTransactionID});
          // Don't set browser = appleEvent because then the next time we call
          // locateBrowser(), we'll get the same AppleEvent, to which we'll
          // already have
          // added the relevant parameter. Instead, regenerate the AppleEvent
          // every time.
          // There's probably a way to do this better; if any has any ideas,
          // please let
          // me know.
          return appleEvent;
        } catch (IllegalAccessException iae) {
          browser = null;
          errorMessage = iae.getMessage();
          return browser;
        } catch (InstantiationException ie) {
          browser = null;
          errorMessage = ie.getMessage();
          return browser;
        } catch (InvocationTargetException ite) {
          browser = null;
          errorMessage = ite.getMessage();
          return browser;
        }
      case MRJ_2_1 :
        File systemFolder;
        try {
          systemFolder = (File) findFolder.invoke(null, new Object[]{kSystemFolderType});
        } catch (IllegalArgumentException iare) {
          browser = null;
          errorMessage = iare.getMessage();
          return browser;
        } catch (IllegalAccessException iae) {
          browser = null;
          errorMessage = iae.getMessage();
          return browser;
        } catch (InvocationTargetException ite) {
          browser = null;
          errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); //$NON-NLS-1$
          return browser;
        }
        String[] systemFolderFiles = systemFolder.list();
        // Avoid a FilenameFilter because that can't be stopped mid-list
        for (int i = 0; i < systemFolderFiles.length; i++) {
          try {
            File file = new File(systemFolder, systemFolderFiles[i]);
            if (!file.isFile()) {
              continue;
            }
            // We're looking for a file with a creator code of 'MACS' and
            // a type of 'FNDR'. Only requiring the type results in non-Finder
            // applications being picked up on certain Mac OS 9 systems,
            // especially German ones, and sending a GURL event to those
            // applications results in a logout under Multiple Users.
            Object fileType = getFileType.invoke(null, new Object[]{file});
            if (FINDER_TYPE.equals(fileType.toString())) {
              Object fileCreator = getFileCreator.invoke(null, new Object[]{file});
              if (FINDER_CREATOR.equals(fileCreator.toString())) {
                browser = file.toString(); // Actually the Finder, but that's OK
                return browser;
              }
            }
          } catch (IllegalArgumentException iare) {
            browser = null;
            errorMessage = iare.getMessage();
            return null;
          } catch (IllegalAccessException iae) {
            browser = null;
            errorMessage = iae.getMessage();
            return browser;
          } catch (InvocationTargetException ite) {
            browser = null;
            errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); //$NON-NLS-1$
            return browser;
          }
        }
        browser = null;
        break;
      case MRJ_3_0 :
      case MRJ_3_1 :
        browser = ""; // Return something non-null //$NON-NLS-1$
        break;
      case WINDOWS_NT :
        browser = "cmd.exe"; //$NON-NLS-1$
        break;
      case WINDOWS_9x :
        browser = "command.com"; //$NON-NLS-1$
        break;
      case OTHER :
      default :
        // On systems other than Windows and the Mac, we try via a rather Unix-
        // specific hack to read the BROWSER environment variable
        // <http://tuxedo.org/~esr/BROWSER/>. If we can't read that variable or
        // it isn't set, we use Netscape.
        // Note: This is commented out for now. It'll work soon.
        browser = getEnvironmentBrowser();
        if (browser == null) {
          browser = "netscape"; //$NON-NLS-1$
        }
        break;
    }
    return browser;
  }

  /**
   * Attempts to open the default web browser to the given URL.
   *
   * @param url
   *          The URL to open
   * @throws IOException
   *           If the web browser could not be located or does not run
   */
  public static void openURL(String url) throws IOException {
    if (!loadedWithoutErrors) {
      throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.exceptionFindingBrowser"), new Object[] { errorMessage })); //$NON-NLS-1$
    }


    if(browserCommand != null) {
      String[] cmd = splitString(browserCommand, ' ', '"', '\\');
      String[] cmde = new String[cmd.length + 1];
      System.arraycopy(cmd, 0, cmde, 0 , cmd.length);
      cmde[cmd.length] = url;
      Runtime.getRuntime().exec(cmde);
      return;
    }

    Object browser = locateBrowser();
    if (browser == null) {
      throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.unableToLocateBrowser"), new Object[] { errorMessage } ) ); //$NON-NLS-1$
    }

    switch (jvm) {
      case MRJ_2_0 :
        Object aeDesc = null;
        try {
          aeDesc = aeDescConstructor.newInstance(new Object[]{url});
          putParameter.invoke(browser, new Object[]{keyDirectObject, aeDesc});
          sendNoReply.invoke(browser, new Object[]{});
        } catch (InvocationTargetException ite) {
          throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.invocationTargetException"), new Object[] { ite.getMessage() } ) ); //$NON-NLS-1$
        } catch (IllegalAccessException iae) {
          throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.illegalAccess"), new Object[] { iae.getMessage() } )); //$NON-NLS-1$
        } catch (InstantiationException ie) {
          throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.instantiation"), new Object[] { ie.getMessage() } )); //$NON-NLS-1$
        } finally {
          aeDesc = null; // Encourage it to get disposed if it was created
          browser = null; // Ditto
        }
        break;
      case MRJ_2_1 :
        Runtime.getRuntime().exec(new String[]{(String) browser, url});
        break;
      case MRJ_3_0 :
        int[] instance = new int[1];
        int result = ICStart(instance, 0);
        if (result == 0) {
          int[] selectionStart = new int[]{0};
          byte[] urlBytes = url.getBytes();
          int[] selectionEnd = new int[]{urlBytes.length};
          result = ICLaunchURL(instance[0], new byte[]{0}, urlBytes, urlBytes.length, selectionStart, selectionEnd);
          if (result == 0) {
            // Ignore the return value; the URL was launched successfully
            // regardless of what happens here.
            ICStop(instance);
          } else {
            throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.cannotLaunchURL"), new Object[] { new Integer(result) } )); //$NON-NLS-1$
          }
        } else {
          throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.cannotCreateNetConfg"), new Object[] { new Integer(result) } ) ); //$NON-NLS-1$
        }
        break;
      case MRJ_3_1 :
      case MRJ_COCOA :
        try {
          openURL.invoke(null, new Object[]{url});
        } catch (InvocationTargetException ite) {
          throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.cannotOpenURL"), new Object[] { ite.getMessage() } ) ); //$NON-NLS-1$
        } catch (IllegalAccessException iae) {
          throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.ilegalAccessOpeningURL"), new Object[] { iae.getMessage() } ) ); //$NON-NLS-1$
        }
        break;
      case WINDOWS_NT :
      case WINDOWS_9x :
        // Add quotes around the URL to allow ampersands and other special
        // characters to work.
        String[] arguments;
        if (jvm == WINDOWS_9x) {
          arguments = new String[]{(String) browser, FIRST_WINDOWS_PARAMETER, SECOND_WINDOWS_PARAMETER, null};
        } else {
          arguments = new String[]{(String) browser, FIRST_WINDOWS_PARAMETER, SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
              null};
        }
        arguments[arguments.length - 1] = '"' + url + '"';
        Process process = Runtime.getRuntime().exec(arguments);
        // This avoids a memory leak on some versions of Java on Windows.
        // That's hinted at in
        // <http://developer.java.sun.com/developer/qow/archive/68/>.
        try {
          process.waitFor();
          process.exitValue();
        } catch (InterruptedException ie) {
          throw new IOException(Messages.getString("BrowserLauncher.interruptedLaunchingBrowser") + ie.getMessage()); //$NON-NLS-1$
        }
        break;
      case OTHER :
        // Assume that we're on Unix and that Netscape is installed

        // Attempt to open the URL in a currently running session of Netscape
        process = Runtime.getRuntime().exec(
            new String[]{(String) browser, NETSCAPE_REMOTE_PARAMETER,
                NETSCAPE_OPEN_PARAMETER_START + url + NETSCAPE_OPEN_PARAMETER_END});
        try {
          int exitCode = process.waitFor();
          if (exitCode != 0) { // if Netscape was not open
            Runtime.getRuntime().exec(new String[]{(String) browser, url});
          }
        } catch (InterruptedException ie) {
          throw new IOException(MessageFormat.format(Messages.getString("BrowserLauncher.interruptedLaunchingBrowser"), new Object[] { ie.getMessage() } ) ); //$NON-NLS-1$
        }
        break;
      default :
        // This should never occur, but if it does, we'll try the simplest thing
        // possible
        Runtime.getRuntime().exec(new String[]{(String) browser, url});
        break;
    }
  }

  /**
   * Tries to read the BROWSER environment variable, which should be set to the
   * absolute path of the user's preferred web browser as proposed at
   * <http://tuxedo.org/~esr/BROWSER/>.
   *
   * @return The value of the BROWSER environment variable, or null if the
   *         variable does not exist or can't be read.
   */
  private static String getEnvironmentBrowser() {
    String browser = null;
    try {
      String[] echoParams = {"/bin/sh", "-c", "echo ${BROWSER:-netscape}"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      Process echoProcess = Runtime.getRuntime().exec(echoParams);
      InputStream echoStream = echoProcess.getInputStream();
      BufferedReader echoReader = new BufferedReader(new InputStreamReader(echoStream));
      browser = echoReader.readLine();
      echoReader.close();
    } catch (Throwable t) {
      // If anything goes wrong, we'll return null.
    }
    return browser;
  }

  /**
   * Methods required for Mac OS X 10.0.x. The presence of native methods does
   * not cause any problems on other platforms.
   */
  private native static int ICStart(int[] instance, int signature);
  private native static int ICStop(int[] instance);
  private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len, int[] selectionStart, int[] selectionEnd);
}
TOP

Related Classes of com.adito.agent.client.util.BrowserLauncher

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.