JAL-4001 GA4 tracking is now ENABLED. Currently logging a page_view like the website...
[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 boolean useGA4 = true;
925
926   /**
927    * Initialise the google tracker if it is not done already.
928    */
929   public static void initGoogleTracker()
930   {
931     if (useGA4)
932     {
933       GoogleAnalytics4.setEnabled(true);
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       GoogleAnalytics4 ga4 = GoogleAnalytics4.getInstance();
942
943       // This will add a page_view similar to the old UA analytics.
944       // We probably want to get rid of this once the application_launch event
945       // is being processed properly.
946       ga4.sendAnalytics("page_view", "page_location", path, "page_title",
947               APPLICATION_STARTED);
948
949       // This will send a new "application_launch" event with parameters
950       // including the old-style "path", the channel name and version
951       ga4.sendAnalytics("application_launch", "page_location", path);
952     }
953     else
954     {
955       if (tracker == null)
956       {
957         if (jgoogleanalyticstracker == null)
958         {
959           // try to get the tracker class
960           try
961           {
962             jgoogleanalyticstracker = Cache.class.getClassLoader()
963                     .loadClass(
964                             "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
965             trackerfocus = Cache.class.getClassLoader().loadClass(
966                     "com.boxysystems.jgoogleanalytics.FocusPoint");
967           } catch (Exception e)
968           {
969             Console.debug(
970                     "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
971             tracker = null;
972             jgoogleanalyticstracker = null;
973             trackerfocus = null;
974             return;
975           }
976         }
977         // now initialise tracker
978         Exception re = null, ex = null;
979         Error err = null;
980         String vrs = "No Version Accessible";
981         try
982         {
983           // Google analytics tracking code for Library Finder
984           tracker = jgoogleanalyticstracker
985                   .getConstructor(new Class[]
986                   { String.class, String.class, String.class })
987                   .newInstance(new Object[]
988                   { ChannelProperties.getProperty("app_name") + " Desktop",
989                       (vrs = Cache.getProperty("VERSION") + "_"
990                               + Cache.getDefault("BUILD_DATE", "unknown")),
991                       "UA-9060947-1" });
992           jgoogleanalyticstracker
993                   .getMethod("trackAsynchronously", new Class[]
994                   { trackerfocus })
995                   .invoke(tracker, new Object[]
996                   { trackerfocus
997                           .getConstructor(new Class[]
998                           { String.class })
999                           .newInstance(new Object[]
1000                           { APPLICATION_STARTED }) });
1001         } catch (RuntimeException e)
1002         {
1003           re = e;
1004         } catch (Exception e)
1005         {
1006           ex = e;
1007         } catch (Error e)
1008         {
1009           err = e;
1010         }
1011         if (re != null || ex != null || err != null)
1012         {
1013           if (re != null)
1014           {
1015             Console.debug("Caught runtime exception in googletracker init:",
1016                     re);
1017           }
1018           if (ex != null)
1019           {
1020             Console.warn(
1021                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
1022                             + vrs,
1023                     ex);
1024           }
1025           if (err != null)
1026           {
1027             Console.error(
1028                     "Whilst initing GoogleTracker for Jalview Desktop version "
1029                             + vrs,
1030                     err);
1031           }
1032         }
1033         else
1034         {
1035           Console.debug("Successfully initialised tracker.");
1036         }
1037       }
1038     }
1039   }
1040
1041   private static final String APPLICATION_STARTED = "Application Started.";
1042
1043   /**
1044    * get the user's default colour if available
1045    * 
1046    * @param property
1047    * @param defcolour
1048    * @return
1049    */
1050   public static Color getDefaultColour(String property, Color defcolour)
1051   {
1052     String colprop = getProperty(property);
1053     if (colprop == null)
1054     {
1055       return defcolour;
1056     }
1057     Color col = ColorUtils.parseColourString(colprop);
1058     if (col == null)
1059     {
1060       Console.warn("Couldn't parse '" + colprop + "' as a colour for "
1061               + property);
1062     }
1063     return (col == null) ? defcolour : col;
1064   }
1065
1066   /**
1067    * store a colour as a Jalview user default property
1068    * 
1069    * @param property
1070    * @param colour
1071    */
1072   public static void setColourProperty(String property, Color colour)
1073   {
1074     setProperty(property, jalview.util.Format.getHexString(colour));
1075   }
1076
1077   /**
1078    * Stores a formatted date in a jalview property, using a fixed locale.
1079    * 
1080    * @param propertyName
1081    * @param date
1082    * @return the formatted date string
1083    */
1084   public static String setDateProperty(String propertyName, Date date)
1085   {
1086     String formatted = date_format.format(date);
1087     setProperty(propertyName, formatted);
1088     return formatted;
1089   }
1090
1091   /**
1092    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1093    * format) and returns as a Date, or null if parsing fails
1094    * 
1095    * @param propertyName
1096    * @return
1097    * 
1098    */
1099   public static Date getDateProperty(String propertyName)
1100   {
1101     String val = getProperty(propertyName);
1102     if (val != null)
1103     {
1104       try
1105       {
1106         return date_format.parse(val);
1107       } catch (Exception ex)
1108       {
1109         System.err.println("Invalid or corrupt date in property '"
1110                 + propertyName + "' : value was '" + val + "'");
1111       }
1112     }
1113     return null;
1114   }
1115
1116   /**
1117    * get and parse a property as an integer. send any parsing problems to
1118    * System.err
1119    * 
1120    * @param property
1121    * @return null or Integer
1122    */
1123   public static Integer getIntegerProperty(String property)
1124   {
1125     String val = getProperty(property);
1126     if (val != null && (val = val.trim()).length() > 0)
1127     {
1128       try
1129       {
1130         return Integer.valueOf(val);
1131       } catch (NumberFormatException x)
1132       {
1133         System.err.println("Invalid integer in property '" + property
1134                 + "' (value was '" + val + "')");
1135       }
1136     }
1137     return null;
1138   }
1139
1140   /**
1141    * Set the specified value, or remove it if null or empty. Does not save the
1142    * properties file.
1143    * 
1144    * @param propName
1145    * @param value
1146    */
1147   public static void setOrRemove(String propName, String value)
1148   {
1149     if (propName == null)
1150     {
1151       return;
1152     }
1153     if (value == null || value.trim().length() < 1)
1154     {
1155       Cache.applicationProperties.remove(propName);
1156     }
1157     else
1158     {
1159       Cache.applicationProperties.setProperty(propName, value);
1160     }
1161   }
1162
1163   /**
1164    * Loads in user colour schemes from files.
1165    * 
1166    * @param files
1167    *          a '|'-delimited list of file paths
1168    */
1169   public static void initUserColourSchemes(String files)
1170   {
1171     if (files == null || files.length() == 0)
1172     {
1173       return;
1174     }
1175
1176     // In case colours can't be loaded, we'll remove them
1177     // from the default list here.
1178     StringBuffer coloursFound = new StringBuffer();
1179     StringTokenizer st = new StringTokenizer(files, "|");
1180     while (st.hasMoreElements())
1181     {
1182       String file = st.nextToken();
1183       try
1184       {
1185         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1186         if (ucs != null)
1187         {
1188           if (coloursFound.length() > 0)
1189           {
1190             coloursFound.append("|");
1191           }
1192           coloursFound.append(file);
1193           ColourSchemes.getInstance().registerColourScheme(ucs);
1194         }
1195       } catch (Exception ex)
1196       {
1197         if (!Jalview.quiet())
1198           System.out.println("Error loading User ColourFile\n" + ex);
1199       }
1200     }
1201     if (!files.equals(coloursFound.toString()))
1202     {
1203       if (coloursFound.toString().length() > 1)
1204       {
1205         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1206                 coloursFound.toString());
1207       }
1208       else
1209       {
1210         applicationProperties
1211                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1212       }
1213     }
1214   }
1215
1216   /**
1217    * Initial logging information helper for various versions output
1218    * 
1219    * @param prefix
1220    * @param value
1221    * @param defaultValue
1222    */
1223   private static void appendIfNotNull(StringBuilder sb, String prefix,
1224           String value, String suffix, String defaultValue)
1225   {
1226     if (value == null && defaultValue == null)
1227     {
1228       return;
1229     }
1230     if (prefix != null)
1231       sb.append(prefix);
1232     sb.append(value == null ? defaultValue : value);
1233     if (suffix != null)
1234       sb.append(suffix);
1235   }
1236
1237   /**
1238    * 
1239    * @return Jalview version, build details and JVM platform version for console
1240    */
1241   public static String getVersionDetailsForConsole()
1242   {
1243     StringBuilder sb = new StringBuilder();
1244     sb.append(ChannelProperties.getProperty("app_name"))
1245             .append(" Version: ");
1246     sb.append(Cache.getDefault("VERSION", "TEST"));
1247     sb.append("\n");
1248     sb.append(ChannelProperties.getProperty("app_name"))
1249             .append(" Installation: ");
1250     sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1251     sb.append("\n");
1252     sb.append("Build Date: ");
1253     sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1254     sb.append("\n");
1255     sb.append("Java version: ");
1256     sb.append(System.getProperty("java.version"));
1257     sb.append("\n");
1258     sb.append("Java platform: ");
1259     sb.append(System.getProperty("os.arch"));
1260     sb.append(" ");
1261     sb.append(System.getProperty("os.name"));
1262     sb.append(" ");
1263     sb.append(System.getProperty("os.version"));
1264     sb.append("\n");
1265     appendIfNotNull(sb, "Install4j version: ",
1266             System.getProperty("sys.install4jVersion"), "\n", null);
1267     appendIfNotNull(sb, "Install4j template version: ",
1268             System.getProperty("installer_template_version"), "\n", null);
1269     appendIfNotNull(sb, "Launcher version: ",
1270             System.getProperty("launcher_version"), "\n", null);
1271     LookAndFeel laf = UIManager.getLookAndFeel();
1272     String lafName = laf == null ? "Not obtained" : laf.getName();
1273     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1274     sb.append("LookAndFeel: ");
1275     sb.append(lafName);
1276     sb.append(" (");
1277     sb.append(lafClass);
1278     sb.append(")\n");
1279     appendIfNotNull(sb, "Channel: ",
1280             ChannelProperties.getProperty("channel"), "\n", null);
1281     if (Console.isDebugEnabled()
1282             || !"release".equals(ChannelProperties.getProperty("channel")))
1283     {
1284       appendIfNotNull(sb, "Getdown appdir: ",
1285               System.getProperty("getdowninstanceappdir"), "\n", null);
1286       appendIfNotNull(sb, "Getdown appbase: ",
1287               System.getProperty("getdowninstanceappbase"), "\n", null);
1288       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1289               "\n", "unknown");
1290       appendIfNotNull(sb, "Preferences file: ", propertiesFile, "\n",
1291               "unknown");
1292     }
1293     return sb.toString();
1294   }
1295
1296   /**
1297    * 
1298    * @return build details as reported in splashscreen
1299    */
1300   public static String getBuildDetailsForSplash()
1301   {
1302     // consider returning more human friendly info
1303     // eg 'built from Source' or update channel
1304     return Cache.getDefault("INSTALLATION", "unknown");
1305   }
1306
1307   public static String getStackTraceString(Throwable t)
1308   {
1309     StringWriter sw = new StringWriter();
1310     PrintWriter pw = new PrintWriter(sw);
1311     t.printStackTrace(pw);
1312     return sw.toString();
1313   }
1314
1315   // proxy properties methods
1316   public static void clearProxyProperties()
1317   {
1318     setProxyProperties(null, null, null, null, null, null, null, null,
1319             null);
1320   }
1321
1322   public static void resetProxyProperties()
1323   {
1324     setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1325             startupProxyProperties[2], startupProxyProperties[3],
1326             startupProxyProperties[4],
1327             startupProxyProperties[5] == null ? null
1328                     : startupProxyProperties[5].toCharArray(),
1329             startupProxyProperties[6],
1330             startupProxyProperties[7] == null ? null
1331                     : startupProxyProperties[7].toCharArray(),
1332             startupProxyProperties[8]);
1333     StringBuilder sb = new StringBuilder();
1334     sb.append("Setting proxy properties to: http.proxyHost=")
1335             .append(startupProxyProperties[0]).append(", http.proxyPort=")
1336             .append(startupProxyProperties[1])
1337             .append(startupProxyProperties[4] != null
1338                     && !startupProxyProperties[4].isEmpty()
1339                             ? " [" + startupProxyProperties[4] + "]"
1340                             : "")
1341             .append(", https.proxyHost=").append(startupProxyProperties[2])
1342             .append(", https.proxyPort=").append(startupProxyProperties[3])
1343             .append(startupProxyProperties[6] != null
1344                     && !startupProxyProperties[6].isEmpty()
1345                             ? " [" + startupProxyProperties[6] + "]"
1346                             : "");
1347
1348     Console.debug(sb.toString());
1349   }
1350
1351   public static void setProxyPropertiesFromPreferences()
1352   {
1353     setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1354   }
1355
1356   public static void setProxyPropertiesFromPreferences(
1357           String previousProxyType)
1358   {
1359     String proxyType = Cache.getDefault("USE_PROXY",
1360             Cache.PROXYTYPE_SYSTEM);
1361     if (previousProxyType != null
1362             && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1363                                                          // customProxy
1364             && proxyType.equals(previousProxyType))
1365     {
1366       // no change
1367       return;
1368     }
1369     switch (proxyType)
1370     {
1371     case Cache.PROXYTYPE_NONE:
1372       if (!previousProxyType.equals(proxyType))
1373       {
1374         Console.info("Setting no proxy settings");
1375         Cache.setProxyProperties(null, null, null, null, null, null, null,
1376                 null, null);
1377       }
1378       break;
1379     case Cache.PROXYTYPE_CUSTOM:
1380       // always re-set a custom proxy -- it might have changed, particularly
1381       // password
1382       Console.info("Setting custom proxy settings");
1383       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1384       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1385               Cache.getDefault("PROXY_PORT", null),
1386               Cache.getDefault("PROXY_SERVER_HTTPS", null),
1387               Cache.getDefault("PROXY_PORT_HTTPS", null),
1388               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1389                       : null,
1390               proxyAuthSet ? Cache.proxyAuthPassword : null,
1391               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1392                       : null,
1393               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1394       break;
1395     default: // system proxy settings by default
1396       Console.info("Setting system proxy settings");
1397       Cache.resetProxyProperties();
1398     }
1399   }
1400
1401   public static void setProxyProperties(String httpHost, String httpPort,
1402           String httpsHost, String httpsPort, String httpUser,
1403           char[] httpPassword, String httpsUser, char[] httpsPassword,
1404           String nonProxyHosts)
1405   {
1406     setOrClearSystemProperty("http.proxyHost", httpHost);
1407     setOrClearSystemProperty("http.proxyPort", httpPort);
1408     setOrClearSystemProperty("https.proxyHost", httpsHost);
1409     setOrClearSystemProperty("https.proxyPort", httpsPort);
1410     setOrClearSystemProperty("http.proxyUser", httpUser);
1411     setOrClearSystemProperty("https.proxyUser", httpsUser);
1412     // note: passwords for http.proxyPassword and https.proxyPassword are sent
1413     // via the Authenticator, properties do not need to be set
1414
1415     // are we using a custom proxy (password prompt might be required)?
1416     boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1417             .equals(PROXYTYPE_CUSTOM);
1418
1419     /*
1420      * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1421      * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1422      * is not re-called).
1423      * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1424      * the AuthCache.
1425      * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1426      * ...
1427      * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1428      */
1429     /*
1430     try
1431     {
1432       sun.net.www.protocol.http.AuthCacheValue
1433               .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1434     } catch (Throwable t)
1435     {
1436       Cache.error(t.getMessage());
1437       Cache.debug(getStackTraceString(t));
1438     }
1439     */
1440
1441     if (httpUser != null || httpsUser != null)
1442     {
1443       try
1444       {
1445         char[] displayHttpPw = new char[httpPassword == null ? 0
1446                 : httpPassword.length];
1447         Arrays.fill(displayHttpPw, '*');
1448         Console.debug(
1449                 "CACHE Proxy: setting new Authenticator with httpUser='"
1450                         + httpUser + "' httpPassword='" + displayHttpPw
1451                         + "'");
1452         if (!Platform.isJS())
1453         /* *
1454          * java.net.Authenticator not implemented in SwingJS yet
1455          * 
1456          * @j2sIgnore
1457          * 
1458          */
1459         {
1460           Authenticator.setDefault(new Authenticator()
1461           {
1462             @Override
1463             protected PasswordAuthentication getPasswordAuthentication()
1464             {
1465               if (getRequestorType() == RequestorType.PROXY)
1466               {
1467                 String protocol = getRequestingProtocol();
1468                 boolean needProxyPasswordSet = false;
1469                 if (customProxySet &&
1470                 // we have a username but no password for the scheme being
1471                 // requested
1472                         (protocol.equalsIgnoreCase("http")
1473                                 && (httpUser != null
1474                                         && httpUser.length() > 0
1475                                         && (httpPassword == null
1476                                                 || httpPassword.length == 0)))
1477                         || (protocol.equalsIgnoreCase("https")
1478                                 && (httpsUser != null
1479                                         && httpsUser.length() > 0
1480                                         && (httpsPassword == null
1481                                                 || httpsPassword.length == 0))))
1482                 {
1483                   // open Preferences -> Connections
1484                   String message = MessageManager
1485                           .getString("label.proxy_password_required");
1486                   Preferences.openPreferences(
1487                           Preferences.TabRef.CONNECTIONS_TAB, message);
1488                   Preferences.getInstance()
1489                           .proxyAuthPasswordCheckHighlight(true, true);
1490                 }
1491                 else
1492                 {
1493                   try
1494                   {
1495                     if (protocol.equalsIgnoreCase("http")
1496                             && getRequestingHost()
1497                                     .equalsIgnoreCase(httpHost)
1498                             && getRequestingPort() == Integer
1499                                     .valueOf(httpPort))
1500                     {
1501                       Console.debug(
1502                               "AUTHENTICATOR returning PasswordAuthentication(\""
1503                                       + httpUser + "\", '"
1504                                       + new String(displayHttpPw) + "')");
1505                       return new PasswordAuthentication(httpUser,
1506                               httpPassword);
1507                     }
1508                     if (protocol.equalsIgnoreCase("https")
1509                             && getRequestingHost()
1510                                     .equalsIgnoreCase(httpsHost)
1511                             && getRequestingPort() == Integer
1512                                     .valueOf(httpsPort))
1513                     {
1514                       char[] displayHttpsPw = new char[httpPassword.length];
1515                       Arrays.fill(displayHttpsPw, '*');
1516                       Console.debug(
1517                               "AUTHENTICATOR returning PasswordAuthentication(\""
1518                                       + httpsUser + "\", '" + displayHttpsPw
1519                                       + "'");
1520                       return new PasswordAuthentication(httpsUser,
1521                               httpsPassword);
1522                     }
1523                   } catch (NumberFormatException e)
1524                   {
1525                     Console.error("Problem with proxy port values [http:"
1526                             + httpPort + ", https:" + httpsPort + "]");
1527                   }
1528                   Console.debug(
1529                           "AUTHENTICATOR after trying to get PasswordAuthentication");
1530                 }
1531               }
1532               // non proxy request
1533               Console.debug("AUTHENTICATOR returning null");
1534               return null;
1535             }
1536           });
1537         } // end of j2sIgnore for java.net.Authenticator
1538
1539         // required to re-enable basic authentication (should be okay for a
1540         // local proxy)
1541         Console.debug(
1542                 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1543         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1544       } catch (SecurityException e)
1545       {
1546         Console.error("Could not set default Authenticator");
1547         Console.debug(getStackTraceString(e));
1548       }
1549     }
1550     else
1551     {
1552       // reset the Authenticator to protect http.proxyUser and
1553       // http.proxyPassword Just In Case
1554       /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1555        * has working credentials. No workaround for Java 11.
1556        */
1557       if (!Platform.isJS())
1558       /* *
1559        * java.net.Authenticator not implemented in SwingJS yet
1560        * 
1561        * @j2sIgnore
1562        * 
1563        */
1564       {
1565         Console.debug(
1566                 "AUTHENTICATOR setting default Authenticator to null");
1567         Authenticator.setDefault(null);
1568       }
1569     }
1570
1571     // nonProxyHosts not currently configurable in Preferences
1572     Console.debug(
1573             "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1574                     + nonProxyHosts + "\"");
1575     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1576   }
1577
1578   public static void setOrClearSystemProperty(String key, char[] value)
1579   {
1580     setOrClearSystemProperty(key,
1581             (value == null) ? null : new String(value));
1582   }
1583
1584   public static void setOrClearSystemProperty(String key, String value)
1585   {
1586     if (key == null)
1587     {
1588       return;
1589     }
1590     if (value == null)
1591     {
1592       System.clearProperty(key);
1593     }
1594     else
1595     {
1596       System.setProperty(key, value);
1597     }
1598   }
1599
1600   /**
1601    * Getdown appbase methods
1602    */
1603
1604   private static final String releaseAppbase;
1605
1606   private static String getdownAppbase;
1607
1608   private static String getdownDistDir;
1609
1610   static
1611   {
1612     if (!Platform.isJS())
1613     {
1614       Float specversion = Float
1615               .parseFloat(System.getProperty("java.specification.version"));
1616       releaseAppbase = (specversion < 9)
1617               ? "https://www.jalview.org/getdown/release/1.8"
1618               : "https://www.jalview.org/getdown/release/11";
1619     }
1620     else
1621     {
1622       // this value currenly made up, can be changed to URL that will be
1623       // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1624       releaseAppbase = "https://www.jalview.org/jalview-js";
1625       getdownAppbase = releaseAppbase;
1626       getdownDistDir = "/swingjs/j2s";
1627     }
1628   }
1629
1630   // look for properties (passed in by getdown) otherwise default to release
1631   private static void setGetdownAppbase()
1632   {
1633     if (getdownAppbase != null)
1634     {
1635       return;
1636     }
1637     String appbase = System.getProperty("getdownappbase");
1638     String distDir = System.getProperty("getdowndistdir");
1639     if (appbase == null)
1640     {
1641       appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1642       distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1643     }
1644     if (appbase == null)
1645     {
1646       appbase = releaseAppbase;
1647       distDir = "release";
1648     }
1649     if (appbase.endsWith("/"))
1650     {
1651       appbase = appbase.substring(0, appbase.length() - 1);
1652     }
1653     if (distDir == null)
1654     {
1655       distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1656     }
1657     getdownAppbase = appbase;
1658     getdownDistDir = distDir;
1659   }
1660
1661   public static String getGetdownAppbase()
1662   {
1663     setGetdownAppbase();
1664     return getdownAppbase;
1665   }
1666
1667   public static String getAppbaseBuildProperties()
1668   {
1669     String appbase = getGetdownAppbase();
1670     return appbase + "/" + getdownDistDir + "/build_properties";
1671   }
1672
1673   private static final Collection<String> bootstrapProperties = new ArrayList<>(
1674           Arrays.asList(JALVIEWLOGLEVEL, BOOTSTRAP_TEST));
1675
1676   public static Properties bootstrapProperties(String filename)
1677   {
1678     Properties bootstrapProps = new Properties();
1679     File file = null;
1680     if (filename != null)
1681     {
1682       file = new File(filename);
1683     }
1684     if (file == null || !file.exists())
1685     {
1686       String channelPrefsFilename = ChannelProperties
1687               .getProperty("preferences.filename");
1688       String propertiesFilename = System.getProperty("user.home")
1689               + File.separatorChar + channelPrefsFilename;
1690       file = new File(propertiesFilename);
1691     }
1692     if (file == null || !file.exists())
1693     {
1694       String releasePrefsFilename = fallbackPropertiesFile;
1695       String releasePropertiesFilename = System.getProperty("user.home")
1696               + File.separatorChar + releasePrefsFilename;
1697       file = new File(releasePropertiesFilename);
1698     }
1699
1700     if (filename == null)
1701       return null;
1702     if (!file.exists())
1703     {
1704       System.err.println("Could not load bootstrap preferences file '"
1705               + filename + "'");
1706       return null;
1707     }
1708
1709     try
1710     {
1711       FileInputStream in = new FileInputStream(file.getAbsoluteFile());
1712       Properties props = new Properties();
1713       props.load(in);
1714       for (String prop : bootstrapProperties)
1715       {
1716         if (props.containsKey(prop))
1717           bootstrapProps.put(prop, props.getProperty(prop));
1718       }
1719     } catch (FileNotFoundException e)
1720     {
1721       System.err.println("Could not find bootstrap preferences file '"
1722               + file.getAbsolutePath() + "'");
1723     } catch (IOException e)
1724     {
1725       System.err.println(
1726               "IOException when loading bootstrap preferences file '"
1727                       + file.getAbsolutePath() + "'");
1728     }
1729     return bootstrapProps;
1730   }
1731 }