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