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