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