JAL-3633 Set proxy preferences before web calls in jalview.bin.Jalview. Fixed call...
[jalview.git] / src / jalview / bin / Cache.java
index 85d23df..8269f32 100755 (executable)
  */
 package jalview.bin;
 
-import jalview.datamodel.PDBEntry;
-import jalview.gui.UserDefinedColours;
-import jalview.schemes.ColourSchemeLoader;
-import jalview.schemes.ColourSchemes;
-import jalview.schemes.UserColourScheme;
-import jalview.structure.StructureImportSettings;
-import jalview.urls.IdOrgSettings;
-import jalview.util.ColorUtils;
-import jalview.util.Platform;
-import jalview.ws.sifts.SiftsSettings;
-
 import java.awt.Color;
 import java.io.BufferedReader;
 import java.io.File;
@@ -38,6 +27,10 @@ import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.Authenticator;
+import java.net.PasswordAuthentication;
 import java.net.URL;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
@@ -48,12 +41,30 @@ import java.util.Locale;
 import java.util.Properties;
 import java.util.StringTokenizer;
 import java.util.TreeSet;
+import java.util.regex.Pattern;
+
+import javax.swing.LookAndFeel;
+import javax.swing.UIManager;
 
 import org.apache.log4j.ConsoleAppender;
 import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
 import org.apache.log4j.SimpleLayout;
 
+import jalview.datamodel.PDBEntry;
+import jalview.gui.Preferences;
+import jalview.gui.UserDefinedColours;
+import jalview.jbgui.GPreferences;
+import jalview.schemes.ColourSchemeLoader;
+import jalview.schemes.ColourSchemes;
+import jalview.schemes.UserColourScheme;
+import jalview.structure.StructureImportSettings;
+import jalview.urls.IdOrgSettings;
+import jalview.util.ColorUtils;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
+import jalview.ws.sifts.SiftsSettings;
+
 /**
  * Stores and retrieves Jalview Application Properties Lists and fields within
  * list entries are separated by '|' symbols unless otherwise stated (|) clauses
@@ -265,6 +276,28 @@ public class Cache
    */
   public static Logger log;
 
+  // save the proxy properties set at startup
+  public final static String[] startupProxyProperties = {
+      System.getProperty("http.proxyHost"),
+      System.getProperty("http.proxyPort"),
+      System.getProperty("https.proxyHost"),
+      System.getProperty("https.proxyPort"),
+      System.getProperty("http.proxyUser"),
+      System.getProperty("http.proxyPassword"),
+      System.getProperty("https.proxyUser"),
+      System.getProperty("https.proxyPassword"),
+      System.getProperty("http.nonProxyHosts") };
+
+  public final static String PROXYTYPE_NONE = "none";
+
+  // "false" and "true" for backward compatibility
+  public final static String PROXYTYPE_SYSTEM = "false";
+
+  public final static String PROXYTYPE_CUSTOM = "true";
+
+  // in-memory only storage of proxy password, safer to use char array
+  public static char[] proxyAuthPassword = null;
+
   /** Jalview Properties */
   public static Properties applicationProperties = new Properties()
   {
@@ -314,7 +347,8 @@ public class Cache
       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
       // Level.INFO.toString())));
       // we shouldn't need to do this
-      org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO); 
+      org.apache.log4j.Logger.getRootLogger()
+              .setLevel(org.apache.log4j.Level.INFO);
 
       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
               .getDefault("logs.Jalview.level", Level.INFO.toString())));
@@ -360,7 +394,7 @@ public class Cache
         InputStream fis;
         try
         {
-          fis = new java.net.URL(propertiesFile).openStream();
+          fis = new URL(propertiesFile).openStream();
           System.out.println(
                   "Loading jalview properties from : " + propertiesFile);
           System.out.println(
@@ -387,16 +421,43 @@ public class Cache
         System.out.println("Error reading properties file: " + ex);
       }
     }
+
+    /* TO BE REPLACED WITH PROXY_TYPE SETTINGS 
     if (getDefault("USE_PROXY", false))
     {
       String proxyServer = getDefault("PROXY_SERVER", ""),
               proxyPort = getDefault("PROXY_PORT", "8080");
+    }
+    */
 
-      System.out.println("Using proxyServer: " + proxyServer
-              + " proxyPort: " + proxyPort);
-
-      System.setProperty("http.proxyHost", proxyServer);
-      System.setProperty("http.proxyPort", proxyPort);
+    // PROXY TYPE settings (now three options "none", "false", "true", but using
+    // backward compatible strings)
+    String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
+    // default to upgrading old settings
+    switch (proxyType)
+    {
+    case PROXYTYPE_NONE:
+      clearProxyProperties();
+      break;
+    case PROXYTYPE_SYSTEM: // use system settings
+      resetProxyProperties();
+      break;
+    case PROXYTYPE_CUSTOM: // use specified proxy settings
+      String httpHost = getDefault("PROXY_SERVER", "");
+      String httpPort = getDefault("PROXY_PORT", "8080");
+      String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
+      String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
+      String httpUser = getDefault("PROXY_AUTH_USER", null);
+      // https.proxyUser and https.proxyPassword are not able to be
+      // independently set in Preferences yet (or http.nonProxyHosts)
+      String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
+      setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
+              proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
+      break;
+    default:
+      String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
+              + proxyType;
+      Cache.warn(message);
     }
 
     // LOAD THE AUTHORS FROM THE authors.props file
@@ -418,9 +479,9 @@ public class Cache
     }
     if (authorDetails == null)
     {
-        applicationProperties.remove("AUTHORS");
-        applicationProperties.remove("AUTHORFNAMES");
-        applicationProperties.remove("YEAR");
+      applicationProperties.remove("AUTHORS");
+      applicationProperties.remove("AUTHORFNAMES");
+      applicationProperties.remove("YEAR");
     }
 
     loadBuildProperties(false);
@@ -453,15 +514,16 @@ public class Cache
 
     String jnlpVersion = System.getProperty("jalview.version");
 
-    // jnlpVersion will be null if a latest version check for the channel needs to
-    // be done
+    // jnlpVersion will be null if a latest version check for the channel needs
+    // to be done
     // Dont do this check if running in headless mode
 
     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
             && (System.getProperty("java.awt.headless") == null || System
                     .getProperty("java.awt.headless").equals("false")))
     {
-      new Thread()
+
+      class VersionChecker extends Thread
       {
         @Override
         public void run()
@@ -509,7 +571,10 @@ public class Cache
 
           setProperty("LATEST_VERSION", remoteVersion);
         }
-      }.start();
+      }
+
+      VersionChecker vc = new VersionChecker();
+      vc.start();
     }
     else
     {
@@ -546,8 +611,8 @@ public class Cache
         url = Cache.class.getResource(resourcePath).toString();
       } catch (Exception ex)
       {
-        System.err.println("Failed to resolve resource " + resourcePath + ": "
-                + ex.getMessage());
+        System.err.println("Failed to resolve resource " + resourcePath
+                + ": " + ex.getMessage());
       }
     }
     else
@@ -596,8 +661,8 @@ public class Cache
     new BuildDetails(codeVersion, null, codeInstallation);
     if (printVersion && reportVersion)
     {
-      System.out
-            .println("Jalview Version: " + codeVersion + codeInstallation);
+      System.out.println(
+              "Jalview Version: " + codeVersion + codeInstallation);
     }
   }
 
@@ -1141,16 +1206,23 @@ public class Cache
   public static String getVersionDetailsForConsole()
   {
     StringBuilder sb = new StringBuilder();
-    sb.append("Jalview Version: " + jalview.bin.Cache.getDefault("VERSION", "TEST"));
+    sb.append("Jalview Version: ");
+    sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
     sb.append("\n");
-    sb.append("Jalview Installation: "
-            + jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
+    sb.append("Jalview Installation: ");
+    sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
     sb.append("\n");
-    sb.append("Build Date: " + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
+    sb.append("Build Date: ");
+    sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
     sb.append("\n");
-    sb.append("Java version: " + System.getProperty("java.version"));
+    sb.append("Java version: ");
+    sb.append(System.getProperty("java.version"));
     sb.append("\n");
-    sb.append(System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
+    sb.append(System.getProperty("os.arch"));
+    sb.append(" ");
+    sb.append(System.getProperty("os.name"));
+    sb.append(" ");
+    sb.append(System.getProperty("os.version"));
     sb.append("\n");
     appendIfNotNull(sb, "Install4j version: ",
             System.getProperty("sys.install4jVersion"), "\n", null);
@@ -1158,7 +1230,19 @@ public class Cache
             System.getProperty("installer_template_version"), "\n", null);
     appendIfNotNull(sb, "Launcher version: ",
             System.getProperty("launcher_version"), "\n", null);
-    if (jalview.bin.Cache.getDefault("VERSION", "TEST").equals("DEVELOPMENT")) {
+    LookAndFeel laf = UIManager.getLookAndFeel();
+    String lafName = laf == null ? "Not obtained" : laf.getName();
+    String lafClass = laf == null ? "unknown" : laf.getClass().getName();
+    sb.append("LookAndFeel: ");
+    sb.append(lafName);
+    sb.append(" (");
+    sb.append(lafClass);
+    sb.append(")\n");
+    // Not displayed in release version ( determined by possible version number
+    // regex 9[9.]*9[.-_a9]* )
+    if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
+            jalview.bin.Cache.getDefault("VERSION", "TEST")))
+    {
       appendIfNotNull(sb, "Getdown appdir: ",
               System.getProperty("getdownappdir"), "\n", null);
       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
@@ -1177,4 +1261,303 @@ public class Cache
     // eg 'built from Source' or update channel
     return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
   }
+
+  public static String getStackTraceString(Throwable t)
+  {
+    StringWriter sw = new StringWriter();
+    PrintWriter pw = new PrintWriter(sw);
+    t.printStackTrace(pw);
+    return sw.toString();
+  }
+
+  // proxy properties methods
+  public static void clearProxyProperties()
+  {
+    setProxyProperties(null, null, null, null, null, null, null, null,
+            null);
+  }
+
+  public static void resetProxyProperties()
+  {
+    setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
+            startupProxyProperties[2], startupProxyProperties[3],
+            startupProxyProperties[4],
+            startupProxyProperties[5] == null ? null
+                    : startupProxyProperties[5].toCharArray(),
+            startupProxyProperties[6],
+            startupProxyProperties[7] == null ? null
+                    : startupProxyProperties[7].toCharArray(),
+            startupProxyProperties[8]);
+    StringBuilder sb = new StringBuilder();
+    sb.append("Setting proxy properties to: http.proxyHost=")
+            .append(startupProxyProperties[0]).append(", http.proxyPort=")
+            .append(startupProxyProperties[1])
+            .append(startupProxyProperties[4] != null
+                    && !startupProxyProperties[4].isEmpty()
+                            ? " [" + startupProxyProperties[4] + "]"
+                            : "")
+            .append(", https.proxyHost=").append(startupProxyProperties[2])
+            .append(", https.proxyPort=").append(startupProxyProperties[3])
+            .append(startupProxyProperties[6] != null
+                    && !startupProxyProperties[6].isEmpty()
+                            ? " [" + startupProxyProperties[6] + "]"
+                            : "");
+
+    Cache.debug(sb.toString());
+  }
+
+  public static void setProxyPropertiesFromPreferences()
+  {
+    setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
+  }
+
+  public static void setProxyPropertiesFromPreferences(
+          String previousProxyType)
+  {
+    String proxyType = Cache.getDefault("USE_PROXY",
+            Cache.PROXYTYPE_SYSTEM);
+    if (proxyType.equals(Cache.PROXYTYPE_NONE))
+    {
+      if (!previousProxyType.equals(proxyType))
+        Cache.log.info("Setting no proxy settings");
+      Cache.setProxyProperties(null, null, null, null, null, null, null,
+              null, null);
+    }
+    else if (proxyType.equals(Cache.PROXYTYPE_CUSTOM))
+    {
+      if (!previousProxyType.equals(proxyType))
+        Cache.log.info("Setting custom proxy settings");
+      boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
+      Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
+              Cache.getDefault("PROXY_PORT", null),
+              Cache.getDefault("PROXY_SERVER_HTTPS", null),
+              Cache.getDefault("PROXY_PORT_HTTPS", null),
+              proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
+                      : null,
+              proxyAuthSet ? Cache.proxyAuthPassword : null,
+              proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
+                      : null,
+              proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
+    }
+    else // systemProxy should be selected and is sensible default anyway
+    {
+      if (!previousProxyType.equals(proxyType))
+        Cache.log.info("Setting system proxy settings");
+      Cache.resetProxyProperties();
+    }
+  }
+
+  public static void setProxyProperties(String httpHost, String httpPort,
+          String httpsHost, String httpsPort, String httpUser,
+          char[] httpPassword, String httpsUser, char[] httpsPassword,
+          String nonProxyHosts)
+  {
+    setOrClearSystemProperty("http.proxyHost", httpHost);
+    setOrClearSystemProperty("http.proxyPort", httpPort);
+    setOrClearSystemProperty("https.proxyHost", httpsHost);
+    setOrClearSystemProperty("https.proxyPort", httpsPort);
+    setOrClearSystemProperty("http.proxyUser", httpUser);
+    setOrClearSystemProperty("http.proxyPassword", httpPassword);
+    setOrClearSystemProperty("https.proxyUser", httpsUser);
+    setOrClearSystemProperty("https.proxyPassword", httpsPassword);
+    // are we using a custom proxy (password prompt might be required)?
+    boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
+            .equals(PROXYTYPE_CUSTOM);
+    if (httpUser != null || httpsUser != null)
+    {
+      try
+      {
+        Authenticator.setDefault(new Authenticator()
+        {
+          @Override
+          protected PasswordAuthentication getPasswordAuthentication()
+          {
+            Cache.debug(
+                    "*** START PasswordAuthentication.getPasswordAuthentication()");
+            Cache.debug("*** getRequestorType()=" + getRequestorType());
+            if (getRequestorType() == RequestorType.PROXY)
+            {
+              String protocol = getRequestingProtocol();
+              boolean needProxyPasswordSet = false;
+              Cache.debug("*** customProxySet = " + customProxySet);
+              Cache.debug("*** protocol = " + protocol);
+              Cache.debug("*** httpUser = " + httpUser);
+              Cache.debug(
+                      "*** httpPassword = \"" + (httpPassword == null ? null
+                              : new String(httpPassword)) + "\"");
+              Cache.debug("*** httpsUser = " + httpsUser);
+              Cache.debug("*** httpsPassword = \""
+                      + (httpsPassword == null ? null
+                              : new String(httpsPassword))
+                      + "\"");
+              if (customProxySet &&
+              // we have a username but no password for the scheme being
+              // requested
+              (protocol.equalsIgnoreCase("http")
+                      && (httpUser != null && httpUser.length() > 0
+                              && (httpPassword == null
+                                      || httpPassword.length == 0)))
+                      || (protocol.equalsIgnoreCase("https")
+                              && (httpsUser != null
+                                      && httpsUser.length() > 0
+                                      && (httpsPassword == null
+                                              || httpsPassword.length == 0))))
+              {
+                // open Preferences -> Connections
+                String message = MessageManager
+                        .getString("label.proxy_password_required");
+                Cache.debug("***+ TRYING TO OPEN PREFERENCES");
+                openPreferencesConnectionsForProxyPassword(message);
+                Cache.debug("***+ AFTER TRYING TO OPEN PREFERENCES");
+              }
+              else
+              {
+                Cache.debug("***+ TRYING TO GET PASSWORDAUTHENTICATION");
+                try
+                {
+                  if (protocol.equalsIgnoreCase("http")
+                          && getRequestingHost().equalsIgnoreCase(httpHost)
+                          && getRequestingPort() == Integer
+                                  .valueOf(httpPort))
+                  {
+                    Cache.debug("***+ RETURNING PasswordAuthentication(\""
+                            + httpUser + "\", \"" + new String(httpPassword)
+                            + "\"");
+                    return new PasswordAuthentication(httpUser,
+                            httpPassword);
+                  }
+                  if (protocol.equalsIgnoreCase("https")
+                          && getRequestingHost().equalsIgnoreCase(httpsHost)
+                          && getRequestingPort() == Integer
+                                  .valueOf(httpsPort))
+                  {
+                    Cache.debug("***+ RETURNING PasswordAuthentication(\""
+                            + httpsUser + "\", \"" + httpsPassword + "\"");
+                    return new PasswordAuthentication(httpsUser,
+                            httpsPassword);
+                  }
+                } catch (NumberFormatException e)
+                {
+                  Cache.error("Problem with proxy port values [http:"
+                          + httpPort + ", https:" + httpsPort + "]");
+                }
+                Cache.debug(
+                        "***+ AFTER TRYING TO GET PASSWORDAUTHENTICATION");
+              }
+            }
+            // non proxy request
+            Cache.debug("***+ Returning null");
+            return null;
+          }
+        });
+        // required to re-enable basic authentication (should be okay for a
+        // local proxy)
+        Cache.debug(
+                "***+ Setting jdk.http.auth.tunneling.disabledSchemes to ''");
+        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
+      } catch (SecurityException e)
+      {
+        Cache.error("Could not set default Authenticator");
+        Cache.debug(getStackTraceString(e));
+      }
+    }
+    else
+    {
+      // reset the Authenticator to protect http.proxyUser and
+      // http.proxyPassword Just In Case
+      Cache.debug("***+ Setting default Authenticator to null");
+      Authenticator.setDefault(null);
+    }
+
+    // nonProxyHosts not currently configurable in Preferences
+    Cache.debug("***+ Setting http.nonProxyHosts property to \""
+            + nonProxyHosts + "\"");
+    setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
+  }
+
+  private static void openPreferencesConnectionsForProxyPassword(
+          String message)
+  {
+    //
+    Cache.info("Opening Preferences for proxy password");
+    // Desktop.instance.preferences_actionPerformed(null);
+    Cache.debug("***+########## TRYING TO OPEN PREFERENCES: " + message);
+    Preferences p = new Preferences(GPreferences.CONNECTIONS_TAB, message);
+    p.grabFocus();
+  }
+
+  public static void setOrClearSystemProperty(String key, char[] value)
+  {
+    setOrClearSystemProperty(key,
+            (value == null) ? null : new String(value));
+  }
+
+  public static void setOrClearSystemProperty(String key, String value)
+  {
+    if (key == null)
+    {
+      return;
+    }
+    if (value == null)
+    {
+      System.clearProperty(key);
+    }
+    else
+    {
+      System.setProperty(key, value);
+    }
+  }
+
+  public final static int DEBUG = 10;
+
+  public final static int INFO = 20;
+
+  public final static int WARN = 30;
+
+  public final static int ERROR = 40;
+
+  public static boolean println(int level, String message)
+  {
+    if (Cache.log == null)
+    {
+      if (level >= ERROR)
+        System.err.println(message);
+      else
+        System.out.println(message);
+      return false;
+    }
+    if (level >= WARN)
+    {
+      Cache.log.warn(message);
+    }
+    else if (level >= INFO)
+    {
+      Cache.log.info(message);
+    }
+    else
+    {
+      Cache.log.debug(message);
+    }
+    return true;
+  }
+
+  public static void debug(String message)
+  {
+    println(DEBUG, message);
+  }
+
+  public static void info(String message)
+  {
+    println(INFO, message);
+  }
+
+  public static void warn(String message)
+  {
+    println(WARN, message);
+  }
+
+  public static void error(String message)
+  {
+    println(ERROR, message);
+  }
 }