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