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