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