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