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