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