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