JAL-3633 Set proxy preferences before web calls in jalview.bin.Jalview. Fixed call...
[jalview.git] / src / jalview / bin / Cache.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import java.awt.Color;
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.PrintWriter;
31 import java.io.StringWriter;
32 import java.net.Authenticator;
33 import java.net.PasswordAuthentication;
34 import java.text.DateFormat;
35 import java.text.SimpleDateFormat;
36 import java.util.Collections;
37 import java.util.Date;
38 import java.util.Enumeration;
39 import java.util.Locale;
40 import java.util.Properties;
41 import java.util.StringTokenizer;
42 import java.util.TreeSet;
43 import java.util.regex.Pattern;
44
45 import javax.swing.LookAndFeel;
46 import javax.swing.UIManager;
47
48 import org.apache.log4j.ConsoleAppender;
49 import org.apache.log4j.Level;
50 import org.apache.log4j.Logger;
51 import org.apache.log4j.SimpleLayout;
52
53 import jalview.datamodel.PDBEntry;
54 import jalview.gui.Preferences;
55 import jalview.gui.UserDefinedColours;
56 import jalview.jbgui.GPreferences;
57 import jalview.schemes.ColourSchemeLoader;
58 import jalview.schemes.ColourSchemes;
59 import jalview.schemes.UserColourScheme;
60 import jalview.structure.StructureImportSettings;
61 import jalview.urls.IdOrgSettings;
62 import jalview.util.ColorUtils;
63 import jalview.util.MessageManager;
64 import jalview.ws.sifts.SiftsSettings;
65
66 /**
67  * Stores and retrieves Jalview Application Properties Lists and fields within
68  * list entries are separated by '|' symbols unless otherwise stated (|) clauses
69  * are alternative values for a tag. <br>
70  * <br>
71  * Current properties include:
72  * <ul>
73  * <br>
74  * logs.Axis.Level - one of the stringified Levels for log4j controlling the
75  * logging level for axis (used for web services) <br>
76  * </li>
77  * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
78  * the logging level for castor (used for serialization) <br>
79  * </li>
80  * <li>logs.Jalview.Level - Cache.log stringified level. <br>
81  * </li>
82  * <li>SCREEN_WIDTH</li>
83  * <li>SCREEN_HEIGHT</li>
84  * <li>SCREEN_Y=285</li>
85  * <li>SCREEN_X=371</li>
86  * <li>SHOW_FULLSCREEN boolean</li>
87  * <li>FONT_NAME java font name for alignment text display</li>
88  * <li>FONT_SIZE size of displayed alignment text</li>
89  * <li>FONT_STYLE style of font displayed (sequence labels are always
90  * italic)</li>
91  * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
92  * <li>LAST_DIRECTORY last directory for browsing alignment</li>
93  * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
94  * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
95  * <li>SHOW_IDENTITY show percentage identity annotation</li>
96  * <li>SHOW_QUALITY show alignment quality annotation</li>
97  * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
98  * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
99  * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
100  * LABEL_AND_SEQUENCE</li>
101  * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
102  * sequence annotations</li>
103  * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
104  * annotation row</li>
105  * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
106  * <li>DEFAULT_FILE_FORMAT file format used to save</li>
107  * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
108  * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
109  * <li>VERSION the version of the jalview build</li>
110  * <li>BUILD_DATE date of this build</li>
111  * <li>LATEST_VERSION the latest jalview version advertised on the
112  * www.jalview.org</li>
113  * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
114  * descriptions</li>
115  * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
116  * suffix to file</li>
117  * <li>RECENT_URL list of recently retrieved URLs</li>
118  * <li>RECENT_FILE list of recently opened files</li>
119  * <li>USE_PROXY flag for whether a http proxy is to be used</li>
120  * <li>PROXY_SERVER the proxy</li>
121  * <li>PROXY_PORT</li>
122  * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
123  * service</li>
124  * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
125  * service</li>
126  * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
127  * collecting usage statistics</li>
128  * <li>SHOW_OVERVIEW boolean for overview window display</li>
129  * <li>ANTI_ALIAS boolean for smooth fonts</li>
130  * <li>RIGHT_ALIGN_IDS boolean</li>
131  * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
132  * <li>PAD_GAPS boolean</li>
133  * <li>ID_ITALICS boolean</li>
134  * <li>SHOW_JV_SUFFIX</li>
135  * <li>WRAP_ALIGNMENT</li>
136  * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
137  * style check</li>
138  * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
139  * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
140  * $SEQUENCE_ID$</li>
141  * <li>STORED_LINKS list of name|url pairs which user has entered but are not
142  * currently used
143  * <li>DEFAULT_LINK name of single url to be used when user double clicks a
144  * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
145  * <li>GROUP_LINKS list of name|URL[|&lt;separator&gt;] tuples - see
146  * jalview.utils.GroupURLLink for more info</li>
147  * <li>DEFAULT_BROWSER for unix</li>
148  * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
149  * (false)</li>
150  * <li>VERSION_CHECK (true) check for the latest release version from
151  * www.jalview.org (or the alias given by the www.jalview.org property)</li>
152  * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
153  * ID tooltip</li>
154  * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
155  * ID tooltip</li>
156  * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
157  * displayed as '.'</li>
158  * <li>SORT_BY_TREE (false) sort the current alignment view according to the
159  * order of a newly displayed tree</li>
160  * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
161  * sequence ID strings before attempting retrieval from any datasource</li>
162  * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
163  * alignment.</li>
164  * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
165  * in the alignment.</li>
166  * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
167  * histogram.</li>
168  * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
169  * logo.</li>
170  * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
171  * logo normalised to row height rather than histogram height.</li>
172  * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
173  * respond to selections made in other alignments containing the same sequences.
174  * </li>
175  * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
176  * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
177  * warning dialog box is displayed.</li>
178  * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
179  * when shading by annotation</li>
180  * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
181  * when shading by annotation</li>
182  * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
183  * requests to be redirected to a mirror of http://www.jalview.org</li>
184  * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
185  * alignment figure to accommodate even the longest sequence ID or annotation
186  * label.</li>
187  * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
188  * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
189  * will override this).</li>
190  * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
191  * record</li>
192  * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
193  * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
194  * display</li>
195  * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
196  * display</li>
197  * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
198  * display</li>
199  * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
200  * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
201  * </li>
202  * 
203  * </ul>
204  * Deprecated settings:
205  * <ul>
206  * *
207  * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
208  * startup (JWS1 services only)</li>
209  * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
210  * (JWS1 services only)</li>
211  * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
212  * services in the desktop GUI</li>
213  * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
214  * panel in web service preferences</li>
215  * </ul>
216  * 
217  * @author $author$
218  * @version $Revision$
219  */
220 public class Cache
221 {
222   /**
223    * property giving log4j level for CASTOR loggers
224    */
225   public static final String CASTORLOGLEVEL = "logs.Castor.level";
226
227   /**
228    * property giving log4j level for AXIS loggers
229    */
230   public static final String AXISLOGLEVEL = "logs.Axis.level";
231
232   /**
233    * property giving log4j level for Jalview Log
234    */
235   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
236
237   /**
238    * Sifts settings
239    */
240   public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
241           .getProperty("user.home") + File.separatorChar
242           + ".sifts_downloads" + File.separatorChar;
243
244   private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
245
246   private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
247
248   /**
249    * Identifiers.org download settings
250    */
251   private static final String ID_ORG_FILE = System.getProperty("user.home")
252           + File.separatorChar + ".identifiers.org.ids.json";
253
254   /**
255    * Allowed values are PDB or mmCIF
256    */
257   private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
258           .toString();
259
260   private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
261           .toString();
262
263   /*
264    * a date formatter using a fixed (rather than the user's) locale; 
265    * this ensures that date properties can be written and re-read successfully
266    * even if the user changes their locale setting
267    */
268   private static final DateFormat date_format = SimpleDateFormat
269           .getDateTimeInstance(SimpleDateFormat.MEDIUM,
270                   SimpleDateFormat.MEDIUM, Locale.UK);
271
272   /**
273    * Initialises the Jalview Application Log
274    */
275   public static Logger log;
276
277   // save the proxy properties set at startup
278   public final static String[] startupProxyProperties = {
279       System.getProperty("http.proxyHost"),
280       System.getProperty("http.proxyPort"),
281       System.getProperty("https.proxyHost"),
282       System.getProperty("https.proxyPort"),
283       System.getProperty("http.proxyUser"),
284       System.getProperty("http.proxyPassword"),
285       System.getProperty("https.proxyUser"),
286       System.getProperty("https.proxyPassword"),
287       System.getProperty("http.nonProxyHosts") };
288
289   public final static String PROXYTYPE_NONE = "none";
290
291   // "false" and "true" for backward compatibility
292   public final static String PROXYTYPE_SYSTEM = "false";
293
294   public final static String PROXYTYPE_CUSTOM = "true";
295
296   // in-memory only storage of proxy password, safer to use char array
297   public static char[] proxyAuthPassword = null;
298
299   /** Jalview Properties */
300   public static Properties applicationProperties = new Properties()
301   {
302     // override results in properties output in alphabetical order
303     @Override
304     public synchronized Enumeration<Object> keys()
305     {
306       return Collections.enumeration(new TreeSet<>(super.keySet()));
307     }
308   };
309
310   /** Default file is ~/.jalview_properties */
311   static String propertiesFile;
312
313   private static boolean propsAreReadOnly = false;
314
315   public static void initLogger()
316   {
317     if (log != null)
318     {
319       return;
320     }
321     try
322     {
323       // TODO: redirect stdout and stderr here in order to grab the output of
324       // the log
325
326       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
327               "System.err");
328       ap.setName("JalviewLogger");
329       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
330       // log output
331       Logger laxis = Logger.getLogger("org.apache.axis");
332       Logger lcastor = Logger.getLogger("org.exolab.castor");
333       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
334
335       laxis.setLevel(Level.toLevel(
336               Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
337       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
338               Level.INFO.toString())));
339       lcastor = Logger.getLogger("org.exolab.castor.xml");
340       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
341               Level.INFO.toString())));
342       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
343       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
344       // Level.INFO.toString())));
345       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
346               .getDefault("logs.Jalview.level", Level.INFO.toString())));
347       // laxis.addAppender(ap);
348       // lcastor.addAppender(ap);
349       // jalview.bin.Cache.log.addAppender(ap);
350       // Tell the user that debug is enabled
351       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
352     } catch (Exception ex)
353     {
354       System.err.println("Problems initializing the log4j system\n");
355       ex.printStackTrace(System.err);
356     }
357   }
358
359   /**
360    * Loads properties from the given properties file. Any existing properties
361    * are first cleared.
362    */
363   public static void loadProperties(String propsFile)
364   {
365     propertiesFile = propsFile;
366     if (propsFile == null)
367     {
368       propertiesFile = System.getProperty("user.home") + File.separatorChar
369               + ".jalview_properties";
370     }
371     else
372     {
373       // don't corrupt the file we've been given.
374       propsAreReadOnly = true;
375     }
376
377     try
378     {
379       InputStream fis;
380       try
381       {
382         fis = new java.net.URL(propertiesFile).openStream();
383         System.out.println(
384                 "Loading jalview properties from : " + propertiesFile);
385         System.out.println(
386                 "Disabling Jalview writing to user's local properties file.");
387         propsAreReadOnly = true;
388
389       } catch (Exception ex)
390       {
391         fis = null;
392       }
393       if (fis == null)
394       {
395         fis = new FileInputStream(propertiesFile);
396       }
397       applicationProperties.clear();
398       applicationProperties.load(fis);
399
400       // remove any old build properties
401
402       deleteBuildProperties();
403       fis.close();
404     } catch (Exception ex)
405     {
406       System.out.println("Error reading properties file: " + ex);
407     }
408
409     // PROXY TYPE settings (now three options "none", "false", "true", but using
410     // backward compatible strings)
411     String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
412     // default to upgrading old settings
413     switch (proxyType)
414     {
415     case PROXYTYPE_NONE:
416       clearProxyProperties();
417       break;
418     case PROXYTYPE_SYSTEM: // use system settings
419       resetProxyProperties();
420       break;
421     case PROXYTYPE_CUSTOM: // use specified proxy settings
422       String httpHost = getDefault("PROXY_SERVER", "");
423       String httpPort = getDefault("PROXY_PORT", "8080");
424       String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
425       String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
426       String httpUser = getDefault("PROXY_AUTH_USER", null);
427       // https.proxyUser and https.proxyPassword are not able to be
428       // independently set in Preferences yet (or http.nonProxyHosts)
429       String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
430       setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
431               proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
432       break;
433     default:
434       String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
435               + proxyType;
436       Cache.warn(message);
437     }
438
439     // LOAD THE AUTHORS FROM THE authors.props file
440     try
441     {
442       String authorDetails = "jar:"
443               .concat(Cache.class.getProtectionDomain().getCodeSource()
444                       .getLocation().toString().concat("!/authors.props"));
445
446       java.net.URL localJarFileURL = new java.net.URL(authorDetails);
447
448       InputStream in = localJarFileURL.openStream();
449       applicationProperties.load(in);
450       in.close();
451     } catch (Exception ex)
452     {
453       System.out.println("Error reading author details: " + ex);
454       applicationProperties.remove("AUTHORS");
455       applicationProperties.remove("AUTHORFNAMES");
456       applicationProperties.remove("YEAR");
457     }
458
459     loadBuildProperties(false);
460
461     SiftsSettings
462             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
463
464     SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
465             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
466
467     SiftsSettings.setFailSafePIDThreshold(
468             jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
469                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
470
471     SiftsSettings.setCacheThresholdInDays(
472             jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
473                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
474
475     IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
476             "http://www.jalview.org/services/identifiers"));
477     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
478
479     StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
480             .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
481     StructureImportSettings
482             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
483     // StructureImportSettings
484     // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
485     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
486
487     String jnlpVersion = System.getProperty("jalview.version");
488
489     // jnlpVersion will be null if a latest version check for the channel needs
490     // to be done
491     // Dont do this check if running in headless mode
492
493     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
494             && (System.getProperty("java.awt.headless") == null || System
495                     .getProperty("java.awt.headless").equals("false")))
496     {
497
498       class VersionChecker extends Thread
499       {
500         @Override
501         public void run()
502         {
503           String orgtimeout = System
504                   .getProperty("sun.net.client.defaultConnectTimeout");
505           if (orgtimeout == null)
506           {
507             orgtimeout = "30";
508             System.out.println("# INFO: Setting default net timeout to "
509                     + orgtimeout + " seconds.");
510           }
511           String remoteVersion = null;
512           try
513           {
514             System.setProperty("sun.net.client.defaultConnectTimeout",
515                     "5000");
516             java.net.URL url = new java.net.URL(Cache
517                     .getDefault("www.jalview.org", "http://www.jalview.org")
518                     + "/webstart/jalview.jnlp");
519             BufferedReader in = new BufferedReader(
520                     new InputStreamReader(url.openStream()));
521             String line = null;
522             while ((line = in.readLine()) != null)
523             {
524               if (line.indexOf("jalview.version") == -1)
525               {
526                 continue;
527               }
528
529               line = line.substring(line.indexOf("value=") + 7);
530               line = line.substring(0, line.lastIndexOf("\""));
531               remoteVersion = line;
532               break;
533             }
534           } catch (Exception ex)
535           {
536             System.out.println(
537                     "Non-fatal exception when checking version at www.jalview.org :");
538             System.out.println(ex);
539             remoteVersion = getProperty("VERSION");
540           }
541           System.setProperty("sun.net.client.defaultConnectTimeout",
542                   orgtimeout);
543
544           setProperty("LATEST_VERSION", remoteVersion);
545         }
546       }
547
548       VersionChecker vc = new VersionChecker();
549       vc.start();
550     }
551     else
552     {
553       if (jnlpVersion != null)
554       {
555         setProperty("LATEST_VERSION", jnlpVersion);
556       }
557       else
558       {
559         applicationProperties.remove("LATEST_VERSION");
560       }
561     }
562
563     // LOAD USERDEFINED COLOURS
564     jalview.bin.Cache
565             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
566     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
567             false);
568   }
569
570   public static void loadBuildProperties(boolean reportVersion)
571   {
572     String codeInstallation = getProperty("INSTALLATION");
573     boolean printV = codeInstallation == null;
574
575     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
576     try
577     {
578       String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
579               .getCodeSource().getLocation().toString()
580               .concat("!/.build_properties"));
581
582       java.net.URL localJarFileURL = new java.net.URL(buildDetails);
583
584       InputStream in = localJarFileURL.openStream();
585       applicationProperties.load(in);
586       in.close();
587     } catch (Exception ex)
588     {
589       System.out.println("Error reading build details: " + ex);
590       applicationProperties.remove("VERSION");
591     }
592     String codeVersion = getProperty("VERSION");
593     codeInstallation = getProperty("INSTALLATION");
594
595     if (codeVersion == null)
596     {
597       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
598       codeVersion = "Test";
599       codeInstallation = "";
600     }
601     else
602     {
603       codeInstallation = " (" + codeInstallation + ")";
604     }
605     setProperty("VERSION", codeVersion);
606     new BuildDetails(codeVersion, null, codeInstallation);
607     if (printV && reportVersion)
608     {
609       System.out.println(
610               "Jalview Version: " + codeVersion + codeInstallation);
611     }
612   }
613
614   private static void deleteBuildProperties()
615   {
616     applicationProperties.remove("LATEST_VERSION");
617     applicationProperties.remove("VERSION");
618     applicationProperties.remove("AUTHORS");
619     applicationProperties.remove("AUTHORFNAMES");
620     applicationProperties.remove("YEAR");
621     applicationProperties.remove("BUILD_DATE");
622     applicationProperties.remove("INSTALLATION");
623   }
624
625   /**
626    * Gets Jalview application property of given key. Returns null if key not
627    * found
628    * 
629    * @param key
630    *          Name of property
631    * 
632    * @return Property value
633    */
634   public static String getProperty(String key)
635   {
636     return applicationProperties.getProperty(key);
637   }
638
639   /**
640    * These methods are used when checking if the saved preference is different
641    * to the default setting
642    */
643
644   public static boolean getDefault(String property, boolean def)
645   {
646     String string = getProperty(property);
647     if (string != null)
648     {
649       def = Boolean.valueOf(string).booleanValue();
650     }
651
652     return def;
653   }
654
655   public static int getDefault(String property, int def)
656   {
657     String string = getProperty(property);
658     if (string != null)
659     {
660       try
661       {
662         def = Integer.parseInt(string);
663       } catch (NumberFormatException e)
664       {
665         System.out.println("Error parsing int property '" + property
666                 + "' with value '" + string + "'");
667       }
668     }
669
670     return def;
671   }
672
673   /**
674    * These methods are used when checking if the saved preference is different
675    * to the default setting
676    */
677   public static String getDefault(String property, String def)
678   {
679     String string = getProperty(property);
680     if (string != null)
681     {
682       return string;
683     }
684
685     return def;
686   }
687
688   /**
689    * Stores property in the file "HOME_DIR/.jalview_properties"
690    * 
691    * @param key
692    *          Name of object
693    * @param obj
694    *          String value of property
695    * 
696    * @return previous value of property (or null)
697    */
698   public static Object setProperty(String key, String obj)
699   {
700     Object oldValue = null;
701     try
702     {
703       oldValue = applicationProperties.setProperty(key, obj);
704       if (propertiesFile != null && !propsAreReadOnly)
705       {
706         FileOutputStream out = new FileOutputStream(propertiesFile);
707         applicationProperties.store(out, "---JalviewX Properties File---");
708         out.close();
709       }
710     } catch (Exception ex)
711     {
712       System.out.println(
713               "Error setting property: " + key + " " + obj + "\n" + ex);
714     }
715     return oldValue;
716   }
717
718   /**
719    * remove the specified property from the jalview properties file
720    * 
721    * @param string
722    */
723   public static void removeProperty(String string)
724   {
725     applicationProperties.remove(string);
726     saveProperties();
727   }
728
729   /**
730    * save the properties to the jalview properties path
731    */
732   public static void saveProperties()
733   {
734     if (!propsAreReadOnly)
735     {
736       try
737       {
738         FileOutputStream out = new FileOutputStream(propertiesFile);
739         applicationProperties.store(out, "---JalviewX Properties File---");
740         out.close();
741       } catch (Exception ex)
742       {
743         System.out.println("Error saving properties: " + ex);
744       }
745     }
746   }
747
748   /**
749    * internal vamsas class discovery state
750    */
751   private static int vamsasJarsArePresent = -1;
752
753   /**
754    * Searches for vamsas client classes on class path.
755    * 
756    * @return true if vamsas client is present on classpath
757    */
758   public static boolean vamsasJarsPresent()
759   {
760     if (vamsasJarsArePresent == -1)
761     {
762       try
763       {
764         if (jalview.jbgui.GDesktop.class.getClassLoader()
765                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
766         {
767           jalview.bin.Cache.log.debug(
768                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
769           vamsasJarsArePresent = 1;
770           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
771           lvclient.setLevel(Level.toLevel(Cache
772                   .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
773
774           lvclient.addAppender(log.getAppender("JalviewLogger"));
775           // Tell the user that debug is enabled
776           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
777         }
778       } catch (Exception e)
779       {
780         vamsasJarsArePresent = 0;
781         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
782       }
783     }
784     return (vamsasJarsArePresent > 0);
785   }
786
787   /**
788    * internal vamsas class discovery state
789    */
790   private static int groovyJarsArePresent = -1;
791
792   /**
793    * Searches for vamsas client classes on class path.
794    * 
795    * @return true if vamsas client is present on classpath
796    */
797   public static boolean groovyJarsPresent()
798   {
799     if (groovyJarsArePresent == -1)
800     {
801       try
802       {
803         if (Cache.class.getClassLoader()
804                 .loadClass("groovy.lang.GroovyObject") != null)
805         {
806           jalview.bin.Cache.log.debug(
807                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
808           groovyJarsArePresent = 1;
809           Logger lgclient = Logger.getLogger("groovy");
810           lgclient.setLevel(Level.toLevel(Cache
811                   .getDefault("logs.Groovy.Level", Level.INFO.toString())));
812
813           lgclient.addAppender(log.getAppender("JalviewLogger"));
814           // Tell the user that debug is enabled
815           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
816         }
817       } catch (Error e)
818       {
819         groovyJarsArePresent = 0;
820         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
821       } catch (Exception e)
822       {
823         groovyJarsArePresent = 0;
824         jalview.bin.Cache.log.debug("Groovy Classes are not present");
825       }
826     }
827     return (groovyJarsArePresent > 0);
828   }
829
830   /**
831    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
832    * enabled.
833    */
834   protected static Object tracker = null;
835
836   protected static Class trackerfocus = null;
837
838   protected static Class jgoogleanalyticstracker = null;
839
840   /**
841    * Initialise the google tracker if it is not done already.
842    */
843   public static void initGoogleTracker()
844   {
845     if (tracker == null)
846     {
847       if (jgoogleanalyticstracker == null)
848       {
849         // try to get the tracker class
850         try
851         {
852           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
853                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
854           trackerfocus = Cache.class.getClassLoader()
855                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
856         } catch (Exception e)
857         {
858           log.debug(
859                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
860           tracker = null;
861           jgoogleanalyticstracker = null;
862           trackerfocus = null;
863           return;
864         }
865       }
866       // now initialise tracker
867       Exception re = null, ex = null;
868       Error err = null;
869       String vrs = "No Version Accessible";
870       try
871       {
872         // Google analytics tracking code for Library Finder
873         tracker = jgoogleanalyticstracker
874                 .getConstructor(new Class[]
875                 { String.class, String.class, String.class })
876                 .newInstance(new Object[]
877                 { "Jalview Desktop",
878                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
879                             + jalview.bin.Cache.getDefault("BUILD_DATE",
880                                     "unknown")),
881                     "UA-9060947-1" });
882         jgoogleanalyticstracker
883                 .getMethod("trackAsynchronously", new Class[]
884                 { trackerfocus })
885                 .invoke(tracker, new Object[]
886                 { trackerfocus.getConstructor(new Class[] { String.class })
887                         .newInstance(new Object[]
888                         { "Application Started." }) });
889       } catch (RuntimeException e)
890       {
891         re = e;
892       } catch (Exception e)
893       {
894         ex = e;
895       } catch (Error e)
896       {
897         err = e;
898       }
899       if (re != null || ex != null || err != null)
900       {
901         if (log != null)
902         {
903           if (re != null)
904           {
905             log.debug("Caught runtime exception in googletracker init:",
906                     re);
907           }
908           if (ex != null)
909           {
910             log.warn(
911                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
912                             + vrs,
913                     ex);
914           }
915           if (err != null)
916           {
917             log.error(
918                     "Whilst initing GoogleTracker for Jalview Desktop version "
919                             + vrs,
920                     err);
921           }
922         }
923         else
924         {
925           if (re != null)
926           {
927             System.err.println(
928                     "Debug: Caught runtime exception in googletracker init:"
929                             + vrs);
930             re.printStackTrace();
931           }
932           if (ex != null)
933           {
934             System.err.println(
935                     "Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
936                             + vrs);
937             ex.printStackTrace();
938           }
939
940           if (err != null)
941           {
942             System.err.println(
943                     "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
944                             + vrs);
945             err.printStackTrace();
946           }
947         }
948       }
949       else
950       {
951         log.debug("Successfully initialised tracker.");
952       }
953     }
954   }
955
956   /**
957    * get the user's default colour if available
958    * 
959    * @param property
960    * @param defcolour
961    * @return
962    */
963   public static Color getDefaultColour(String property, Color defcolour)
964   {
965     String colprop = getProperty(property);
966     if (colprop == null)
967     {
968       return defcolour;
969     }
970     Color col = ColorUtils.parseColourString(colprop);
971     if (col == null)
972     {
973       log.warn("Couldn't parse '" + colprop + "' as a colour for "
974               + property);
975     }
976     return (col == null) ? defcolour : col;
977   }
978
979   /**
980    * store a colour as a Jalview user default property
981    * 
982    * @param property
983    * @param colour
984    */
985   public static void setColourProperty(String property, Color colour)
986   {
987     setProperty(property, jalview.util.Format.getHexString(colour));
988   }
989
990   /**
991    * Stores a formatted date in a jalview property, using a fixed locale.
992    * 
993    * @param propertyName
994    * @param date
995    * @return the formatted date string
996    */
997   public static String setDateProperty(String propertyName, Date date)
998   {
999     String formatted = date_format.format(date);
1000     setProperty(propertyName, formatted);
1001     return formatted;
1002   }
1003
1004   /**
1005    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1006    * format) and returns as a Date, or null if parsing fails
1007    * 
1008    * @param propertyName
1009    * @return
1010    * 
1011    */
1012   public static Date getDateProperty(String propertyName)
1013   {
1014     String val = getProperty(propertyName);
1015     if (val != null)
1016     {
1017       try
1018       {
1019         return date_format.parse(val);
1020       } catch (Exception ex)
1021       {
1022         System.err.println("Invalid or corrupt date in property '"
1023                 + propertyName + "' : value was '" + val + "'");
1024       }
1025     }
1026     return null;
1027   }
1028
1029   /**
1030    * get and parse a property as an integer. send any parsing problems to
1031    * System.err
1032    * 
1033    * @param property
1034    * @return null or Integer
1035    */
1036   public static Integer getIntegerProperty(String property)
1037   {
1038     String val = getProperty(property);
1039     if (val != null && (val = val.trim()).length() > 0)
1040     {
1041       try
1042       {
1043         return Integer.valueOf(val);
1044       } catch (NumberFormatException x)
1045       {
1046         System.err.println("Invalid integer in property '" + property
1047                 + "' (value was '" + val + "')");
1048       }
1049     }
1050     return null;
1051   }
1052
1053   /**
1054    * Set the specified value, or remove it if null or empty. Does not save the
1055    * properties file.
1056    * 
1057    * @param propName
1058    * @param value
1059    */
1060   public static void setOrRemove(String propName, String value)
1061   {
1062     if (propName == null)
1063     {
1064       return;
1065     }
1066     if (value == null || value.trim().length() < 1)
1067     {
1068       Cache.applicationProperties.remove(propName);
1069     }
1070     else
1071     {
1072       Cache.applicationProperties.setProperty(propName, value);
1073     }
1074   }
1075
1076   /**
1077    * Loads in user colour schemes from files.
1078    * 
1079    * @param files
1080    *          a '|'-delimited list of file paths
1081    */
1082   public static void initUserColourSchemes(String files)
1083   {
1084     if (files == null || files.length() == 0)
1085     {
1086       return;
1087     }
1088
1089     // In case colours can't be loaded, we'll remove them
1090     // from the default list here.
1091     StringBuffer coloursFound = new StringBuffer();
1092     StringTokenizer st = new StringTokenizer(files, "|");
1093     while (st.hasMoreElements())
1094     {
1095       String file = st.nextToken();
1096       try
1097       {
1098         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1099         if (ucs != null)
1100         {
1101           if (coloursFound.length() > 0)
1102           {
1103             coloursFound.append("|");
1104           }
1105           coloursFound.append(file);
1106           ColourSchemes.getInstance().registerColourScheme(ucs);
1107         }
1108       } catch (Exception ex)
1109       {
1110         System.out.println("Error loading User ColourFile\n" + ex);
1111       }
1112     }
1113     if (!files.equals(coloursFound.toString()))
1114     {
1115       if (coloursFound.toString().length() > 1)
1116       {
1117         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1118                 coloursFound.toString());
1119       }
1120       else
1121       {
1122         applicationProperties
1123                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1124       }
1125     }
1126   }
1127
1128   /**
1129    * Initial logging information helper for various versions output
1130    * 
1131    * @param prefix
1132    * @param value
1133    * @param defaultValue
1134    */
1135   private static void appendIfNotNull(StringBuilder sb, String prefix,
1136           String value, String suffix, String defaultValue)
1137   {
1138     if (value == null && defaultValue == null)
1139     {
1140       return;
1141     }
1142     String line = prefix + (value != null ? value : defaultValue) + suffix;
1143     sb.append(line);
1144   }
1145
1146   /**
1147    * 
1148    * @return Jalview version, build details and JVM platform version for console
1149    */
1150   public static String getVersionDetailsForConsole()
1151   {
1152     StringBuilder sb = new StringBuilder();
1153     sb.append("Jalview Version: ");
1154     sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1155     sb.append("\n");
1156     sb.append("Jalview Installation: ");
1157     sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1158     sb.append("\n");
1159     sb.append("Build Date: ");
1160     sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1161     sb.append("\n");
1162     sb.append("Java version: ");
1163     sb.append(System.getProperty("java.version"));
1164     sb.append("\n");
1165     sb.append(System.getProperty("os.arch"));
1166     sb.append(" ");
1167     sb.append(System.getProperty("os.name"));
1168     sb.append(" ");
1169     sb.append(System.getProperty("os.version"));
1170     sb.append("\n");
1171     appendIfNotNull(sb, "Install4j version: ",
1172             System.getProperty("sys.install4jVersion"), "\n", null);
1173     appendIfNotNull(sb, "Install4j template version: ",
1174             System.getProperty("installer_template_version"), "\n", null);
1175     appendIfNotNull(sb, "Launcher version: ",
1176             System.getProperty("launcher_version"), "\n", null);
1177     LookAndFeel laf = UIManager.getLookAndFeel();
1178     String lafName = laf == null ? "Not obtained" : laf.getName();
1179     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1180     sb.append("LookAndFeel: ");
1181     sb.append(lafName);
1182     sb.append(" (");
1183     sb.append(lafClass);
1184     sb.append(")\n");
1185     // Not displayed in release version ( determined by possible version number
1186     // regex 9[9.]*9[.-_a9]* )
1187     if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1188             jalview.bin.Cache.getDefault("VERSION", "TEST")))
1189     {
1190       appendIfNotNull(sb, "Getdown appdir: ",
1191               System.getProperty("getdownappdir"), "\n", null);
1192       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1193               "\n", "unknown");
1194     }
1195     return sb.toString();
1196   }
1197
1198   /**
1199    * 
1200    * @return build details as reported in splashscreen
1201    */
1202   public static String getBuildDetailsForSplash()
1203   {
1204     // consider returning more human friendly info
1205     // eg 'built from Source' or update channel
1206     return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1207   }
1208
1209   public static String getStackTraceString(Throwable t)
1210   {
1211     StringWriter sw = new StringWriter();
1212     PrintWriter pw = new PrintWriter(sw);
1213     t.printStackTrace(pw);
1214     return sw.toString();
1215   }
1216
1217   // proxy properties methods
1218   public static void clearProxyProperties()
1219   {
1220     setProxyProperties(null, null, null, null, null, null, null, null,
1221             null);
1222   }
1223
1224   public static void resetProxyProperties()
1225   {
1226     setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1227             startupProxyProperties[2], startupProxyProperties[3],
1228             startupProxyProperties[4],
1229             startupProxyProperties[5].toCharArray(),
1230             startupProxyProperties[6],
1231             startupProxyProperties[7].toCharArray(),
1232             startupProxyProperties[8]);
1233     StringBuilder sb = new StringBuilder();
1234     sb.append("Setting proxy properties to: http.proxyHost=")
1235             .append(startupProxyProperties[0]).append(", http.proxyPort=")
1236             .append(startupProxyProperties[1])
1237             .append(startupProxyProperties[4] != null
1238                     && !startupProxyProperties[4].isEmpty()
1239                             ? " [" + startupProxyProperties[4] + "]"
1240                             : "")
1241             .append(", https.proxyHost=").append(startupProxyProperties[2])
1242             .append(", https.proxyPort=").append(startupProxyProperties[3])
1243             .append(startupProxyProperties[6] != null
1244                     && !startupProxyProperties[6].isEmpty()
1245                             ? " [" + startupProxyProperties[6] + "]"
1246                             : "");
1247
1248     Cache.debug(sb.toString());
1249   }
1250
1251   public static void setProxyPropertiesFromPreferences()
1252   {
1253     setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1254   }
1255
1256   public static void setProxyPropertiesFromPreferences(
1257           String previousProxyType)
1258   {
1259     String proxyType = Cache.getDefault("USE_PROXY",
1260             Cache.PROXYTYPE_SYSTEM);
1261     if (proxyType.equals(Cache.PROXYTYPE_NONE))
1262     {
1263       if (!previousProxyType.equals(proxyType))
1264         Cache.log.info("Setting no proxy settings");
1265       Cache.setProxyProperties(null, null, null, null, null, null, null,
1266               null, null);
1267     }
1268     else if (proxyType.equals(Cache.PROXYTYPE_CUSTOM))
1269     {
1270       if (!previousProxyType.equals(proxyType))
1271         Cache.log.info("Setting custom proxy settings");
1272       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1273       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1274               Cache.getDefault("PROXY_PORT", null),
1275               Cache.getDefault("PROXY_SERVER_HTTPS", null),
1276               Cache.getDefault("PROXY_PORT_HTTPS", null),
1277               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1278                       : null,
1279               proxyAuthSet ? Cache.proxyAuthPassword : null,
1280               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1281                       : null,
1282               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1283     }
1284     else // systemProxy should be selected and is sensible default anyway
1285     {
1286       if (!previousProxyType.equals(proxyType))
1287         Cache.log.info("Setting system proxy settings");
1288       Cache.resetProxyProperties();
1289     }
1290   }
1291
1292   public static void setProxyProperties(String httpHost, String httpPort,
1293           String httpsHost, String httpsPort, String httpUser,
1294           char[] httpPassword, String httpsUser, char[] httpsPassword,
1295           String nonProxyHosts)
1296   {
1297     setOrClearSystemProperty("http.proxyHost", httpHost);
1298     setOrClearSystemProperty("http.proxyPort", httpPort);
1299     setOrClearSystemProperty("https.proxyHost", httpsHost);
1300     setOrClearSystemProperty("https.proxyPort", httpsPort);
1301     setOrClearSystemProperty("http.proxyUser", httpUser);
1302     setOrClearSystemProperty("http.proxyPassword", httpPassword);
1303     setOrClearSystemProperty("https.proxyUser", httpsUser);
1304     setOrClearSystemProperty("https.proxyPassword", httpsPassword);
1305     // are we using a custom proxy (password prompt might be required)?
1306     boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1307             .equals(PROXYTYPE_CUSTOM);
1308     if (httpUser != null || httpsUser != null)
1309     {
1310       try
1311       {
1312         Authenticator.setDefault(new Authenticator()
1313         {
1314           @Override
1315           protected PasswordAuthentication getPasswordAuthentication()
1316           {
1317             Cache.debug(
1318                     "*** START PasswordAuthentication.getPasswordAuthentication()");
1319             Cache.debug("*** getRequestorType()=" + getRequestorType());
1320             if (getRequestorType() == RequestorType.PROXY)
1321             {
1322               String protocol = getRequestingProtocol();
1323               boolean needProxyPasswordSet = false;
1324               Cache.debug("*** customProxySet = " + customProxySet);
1325               Cache.debug("*** protocol = " + protocol);
1326               Cache.debug("*** httpUser = " + httpUser);
1327               Cache.debug(
1328                       "*** httpPassword = \"" + (httpPassword == null ? null
1329                               : new String(httpPassword)) + "\"");
1330               Cache.debug("*** httpsUser = " + httpsUser);
1331               Cache.debug("*** httpsPassword = \""
1332                       + (httpsPassword == null ? null
1333                               : new String(httpsPassword))
1334                       + "\"");
1335               if (customProxySet &&
1336               // we have a username but no password for the scheme being
1337               // requested
1338               (protocol.equalsIgnoreCase("http")
1339                       && (httpUser != null && httpUser.length() > 0
1340                               && (httpPassword == null
1341                                       || httpPassword.length == 0)))
1342                       || (protocol.equalsIgnoreCase("https")
1343                               && (httpsUser != null
1344                                       && httpsUser.length() > 0
1345                                       && (httpsPassword == null
1346                                               || httpsPassword.length == 0))))
1347               {
1348                 // open Preferences -> Connections
1349                 String message = MessageManager
1350                         .getString("label.proxy_password_required");
1351                 Cache.debug("***+ TRYING TO OPEN PREFERENCES");
1352                 openPreferencesConnectionsForProxyPassword(message);
1353                 Cache.debug("***+ AFTER TRYING TO OPEN PREFERENCES");
1354               }
1355               else
1356               {
1357                 Cache.debug("***+ TRYING TO GET PASSWORDAUTHENTICATION");
1358                 try
1359                 {
1360                   if (protocol.equalsIgnoreCase("http")
1361                           && getRequestingHost().equalsIgnoreCase(httpHost)
1362                           && getRequestingPort() == Integer
1363                                   .valueOf(httpPort))
1364                   {
1365                     Cache.debug("***+ RETURNING PasswordAuthentication(\""
1366                             + httpUser + "\", \"" + new String(httpPassword)
1367                             + "\"");
1368                     return new PasswordAuthentication(httpUser,
1369                             httpPassword);
1370                   }
1371                   if (protocol.equalsIgnoreCase("https")
1372                           && getRequestingHost().equalsIgnoreCase(httpsHost)
1373                           && getRequestingPort() == Integer
1374                                   .valueOf(httpsPort))
1375                   {
1376                     Cache.debug("***+ RETURNING PasswordAuthentication(\""
1377                             + httpsUser + "\", \"" + httpsPassword + "\"");
1378                     return new PasswordAuthentication(httpsUser,
1379                             httpsPassword);
1380                   }
1381                 } catch (NumberFormatException e)
1382                 {
1383                   Cache.error("Problem with proxy port values [http:"
1384                           + httpPort + ", https:" + httpsPort + "]");
1385                 }
1386                 Cache.debug(
1387                         "***+ AFTER TRYING TO GET PASSWORDAUTHENTICATION");
1388               }
1389             }
1390             // non proxy request
1391             Cache.debug("***+ Returning null");
1392             return null;
1393           }
1394         });
1395         // required to re-enable basic authentication (should be okay for a
1396         // local proxy)
1397         Cache.debug(
1398                 "***+ Setting jdk.http.auth.tunneling.disabledSchemes to ''");
1399         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1400       } catch (SecurityException e)
1401       {
1402         Cache.error("Could not set default Authenticator");
1403         Cache.debug(getStackTraceString(e));
1404       }
1405     }
1406     else
1407     {
1408       // reset the Authenticator to protect http.proxyUser and
1409       // http.proxyPassword Just In Case
1410       Cache.debug("***+ Setting default Authenticator to null");
1411       Authenticator.setDefault(null);
1412     }
1413
1414     // nonProxyHosts not currently configurable in Preferences
1415     Cache.debug("***+ Setting http.nonProxyHosts property to \""
1416             + nonProxyHosts + "\"");
1417     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1418   }
1419
1420   private static void openPreferencesConnectionsForProxyPassword(
1421           String message)
1422   {
1423     //
1424     Cache.info("Opening Preferences for proxy password");
1425     // Desktop.instance.preferences_actionPerformed(null);
1426     Cache.debug("***+########## TRYING TO OPEN PREFERENCES: " + message);
1427     Preferences p = new Preferences(GPreferences.CONNECTIONS_TAB, message);
1428     p.grabFocus();
1429   }
1430
1431   public static void setOrClearSystemProperty(String key, char[] value)
1432   {
1433     setOrClearSystemProperty(key,
1434             (value == null) ? null : new String(value));
1435   }
1436
1437   public static void setOrClearSystemProperty(String key, String value)
1438   {
1439     if (key == null)
1440     {
1441       return;
1442     }
1443     if (value == null)
1444     {
1445       System.clearProperty(key);
1446     }
1447     else
1448     {
1449       System.setProperty(key, value);
1450     }
1451   }
1452
1453   public final static int DEBUG = 10;
1454
1455   public final static int INFO = 20;
1456
1457   public final static int WARN = 30;
1458
1459   public final static int ERROR = 40;
1460
1461   public static boolean println(int level, String message)
1462   {
1463     if (Cache.log == null)
1464     {
1465       if (level >= ERROR)
1466         System.err.println(message);
1467       else
1468         System.out.println(message);
1469       return false;
1470     }
1471     if (level >= WARN)
1472     {
1473       Cache.log.warn(message);
1474     }
1475     else if (level >= INFO)
1476     {
1477       Cache.log.info(message);
1478     }
1479     else
1480     {
1481       Cache.log.debug(message);
1482     }
1483     return true;
1484   }
1485
1486   public static void debug(String message)
1487   {
1488     println(DEBUG, message);
1489   }
1490
1491   public static void info(String message)
1492   {
1493     println(INFO, message);
1494   }
1495
1496   public static void warn(String message)
1497   {
1498     println(WARN, message);
1499   }
1500
1501   public static void error(String message)
1502   {
1503     println(ERROR, message);
1504   }
1505 }