Merge branch 'improvement/JAL-4250_secondary_structure_annotation_antialias' into...
[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             jalview.bin.Console.outPrintln(
411                     "Loading jalview properties from : " + propertiesFile);
412             jalview.bin.Console.outPrintln(
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           jalview.bin.Console
444                   .outPrintln("Error reading properties file: " + ex);
445       }
446     }
447
448     /* TO BE REPLACED WITH PROXY_TYPE SETTINGS 
449     if (getDefault("USE_PROXY", false))
450     {
451       String proxyServer = getDefault("PROXY_SERVER", ""),
452               proxyPort = getDefault("PROXY_PORT", "8080");
453     }
454     */
455
456     // PROXY TYPE settings (now three options "none", "false", "true", but using
457     // backward compatible strings)
458     String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
459     // default to upgrading old settings
460     switch (proxyType)
461     {
462     case PROXYTYPE_NONE:
463       clearProxyProperties();
464       break;
465     case PROXYTYPE_SYSTEM: // use system settings
466       resetProxyProperties();
467       break;
468     case PROXYTYPE_CUSTOM: // use specified proxy settings
469       String httpHost = getDefault("PROXY_SERVER", "");
470       String httpPort = getDefault("PROXY_PORT", "8080");
471       String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
472       String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
473       String httpUser = getDefault("PROXY_AUTH_USER", null);
474       // https.proxyUser and https.proxyPassword are not able to be
475       // independently set in Preferences yet (or http.nonProxyHosts)
476       String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
477       setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
478               proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
479       break;
480     default:
481       String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
482               + proxyType;
483       Console.warn(message);
484     }
485
486     // LOAD THE AUTHORS FROM THE authors.props file
487     String authorDetails = resolveResourceURLFor("/authors.props");
488
489     try
490     {
491       if (authorDetails != null)
492       {
493         URL localJarFileURL = new URL(authorDetails);
494         InputStream in = localJarFileURL.openStream();
495         applicationProperties.load(in);
496         in.close();
497       }
498     } catch (Exception ex)
499     {
500       if (!Jalview.quiet())
501         jalview.bin.Console
502                 .outPrintln("Error reading author details: " + ex);
503       authorDetails = null;
504     }
505     if (authorDetails == null)
506     {
507       applicationProperties.remove("AUTHORS");
508       applicationProperties.remove("AUTHORFNAMES");
509       applicationProperties.remove("YEAR");
510     }
511
512     loadBuildProperties(false);
513
514     SiftsSettings
515             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
516
517     SiftsSettings.setSiftDownloadDirectory(Cache
518             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
519
520     SiftsSettings.setFailSafePIDThreshold(
521             Cache.getDefault("sifts_fail_safe_pid_threshold",
522                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
523
524     SiftsSettings.setCacheThresholdInDays(
525             Cache.getDefault("sifts_cache_threshold_in_days",
526                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
527
528     IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
529             "https://www.jalview.org/services/identifiers"));
530     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
531
532     StructureImportSettings.setDefaultStructureFileFormat(
533             Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
534     StructureImportSettings
535             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
536     // StructureImportSettings
537     // .setDefaultPDBFileParser(Cache.getDefault(
538     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
539
540     String jnlpVersion = System.getProperty("jalview.version");
541
542     // jnlpVersion will be null if a latest version check for the channel needs
543     // to be done
544     // Dont do this check if running in headless mode
545
546     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
547             && (System.getProperty("java.awt.headless") == null || System
548                     .getProperty("java.awt.headless").equals("false")))
549     {
550
551       class VersionChecker extends Thread
552       {
553
554         @Override
555         public void run()
556         {
557           String remoteBuildPropertiesUrl = Cache
558                   .getAppbaseBuildProperties();
559
560           String orgtimeout = System
561                   .getProperty("sun.net.client.defaultConnectTimeout");
562           if (orgtimeout == null)
563           {
564             orgtimeout = "30";
565             Console.debug("Setting default net timeout to " + orgtimeout
566                     + " seconds.");
567           }
568           String remoteVersion = null;
569           if (remoteBuildPropertiesUrl.startsWith("http"))
570           {
571             try
572             {
573               System.setProperty("sun.net.client.defaultConnectTimeout",
574                       "5000");
575
576               URL url = new URL(remoteBuildPropertiesUrl);
577
578               BufferedReader in = new BufferedReader(
579                       new InputStreamReader(url.openStream()));
580
581               Properties remoteBuildProperties = new Properties();
582               remoteBuildProperties.load(in);
583               remoteVersion = remoteBuildProperties.getProperty("VERSION");
584             } catch (Exception ex)
585             {
586               if (!Jalview.quiet())
587               {
588                 jalview.bin.Console.outPrintln(
589                         "Non-fatal exception when checking version at "
590                                 + remoteBuildPropertiesUrl + ":");
591                 jalview.bin.Console.printStackTrace(ex);
592               }
593               remoteVersion = getProperty("VERSION");
594             }
595           }
596           System.setProperty("sun.net.client.defaultConnectTimeout",
597                   orgtimeout);
598
599           setProperty("LATEST_VERSION", remoteVersion);
600         }
601       }
602
603       VersionChecker vc = new VersionChecker();
604       vc.start();
605     }
606     else
607     {
608       if (jnlpVersion != null)
609       {
610         setProperty("LATEST_VERSION", jnlpVersion);
611       }
612       else
613       {
614         applicationProperties.remove("LATEST_VERSION");
615       }
616     }
617
618     // LOAD USERDEFINED COLOURS
619     Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
620     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
621             false);
622   }
623
624   /**
625    * construct a resource URL for the given absolute resource pathname
626    * 
627    * @param resourcePath
628    * @return
629    */
630   private static String resolveResourceURLFor(String resourcePath)
631   {
632     String url = null;
633     if (Platform.isJS() || !Cache.class.getProtectionDomain()
634             .getCodeSource().getLocation().toString().endsWith(".jar"))
635     {
636       try
637       {
638         url = Cache.class.getResource(resourcePath).toString();
639       } catch (Exception ex)
640       {
641         jalview.bin.Console.errPrintln("Failed to resolve resource " + resourcePath
642                 + ": " + ex.getMessage());
643       }
644     }
645     else
646     {
647       url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
648               .getLocation().toString().concat("!" + resourcePath));
649     }
650     return url;
651   }
652
653   public static void loadBuildProperties(boolean reportVersion)
654   {
655     String codeInstallation = getProperty("INSTALLATION");
656     boolean printVersion = codeInstallation == null;
657
658     /*
659      * read build properties - from the Jalview jar for a Java distribution,
660      * or from codebase file in test or JalviewJS context
661      */
662     try
663     {
664       String buildDetails = resolveResourceURLFor("/.build_properties");
665       URL localJarFileURL = new URL(buildDetails);
666       InputStream in = localJarFileURL.openStream();
667       buildProperties.load(in);
668       in.close();
669       if (buildProperties.getProperty("BUILD_DATE", null) != null)
670       {
671         applicationProperties.put("BUILD_DATE",
672                 buildProperties.getProperty("BUILD_DATE"));
673       }
674       if (buildProperties.getProperty("INSTALLATION", null) != null)
675       {
676         applicationProperties.put("INSTALLATION",
677                 buildProperties.getProperty("INSTALLATION"));
678       }
679       if (buildProperties.getProperty("VERSION", null) != null)
680       {
681         applicationProperties.put("VERSION",
682                 buildProperties.getProperty("VERSION"));
683       }
684       if (buildProperties.getProperty("JAVA_COMPILE_VERSION", null) != null)
685       {
686         applicationProperties.put("JAVA_COMPILE_VERSION",
687                 buildProperties.getProperty("JAVA_COMPILE_VERSION"));
688       }
689     } catch (Exception ex)
690     {
691       if (!Jalview.quiet())
692         jalview.bin.Console
693                 .outPrintln("Error reading build details: " + ex);
694       applicationProperties.remove("VERSION");
695     }
696     String codeVersion = getProperty("VERSION");
697     codeInstallation = getProperty("INSTALLATION");
698
699     if (codeVersion == null)
700     {
701       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
702       codeVersion = "Test";
703       codeInstallation = "";
704     }
705     else
706     {
707       codeInstallation = " (" + codeInstallation + ")";
708     }
709     setProperty("VERSION", codeVersion);
710     new BuildDetails(codeVersion, null, codeInstallation);
711     if (printVersion && reportVersion)
712     {
713       jalview.bin.Console
714               .outPrintln(ChannelProperties.getProperty("app_name")
715                       + " version: " + codeVersion + codeInstallation);
716     }
717   }
718
719   private static void deleteBuildProperties()
720   {
721     applicationProperties.remove("LATEST_VERSION");
722     applicationProperties.remove("VERSION");
723     applicationProperties.remove("AUTHORS");
724     applicationProperties.remove("AUTHORFNAMES");
725     applicationProperties.remove("YEAR");
726     applicationProperties.remove("BUILD_DATE");
727     applicationProperties.remove("INSTALLATION");
728   }
729
730   /**
731    * Gets Jalview application property of given key. Returns null if key not
732    * found
733    * 
734    * @param key
735    *          Name of property
736    * 
737    * @return Property value
738    */
739   public static String getProperty(String key)
740   {
741     return getProperty(key, false);
742   }
743
744   public static String getProperty(String key,
745           boolean skipSessionProperties)
746   {
747     String prop = null;
748     if (!(skipSessionProperties || bypassSessionProperties))
749     {
750       prop = getSessionProperty(key);
751     }
752     if (prop == null)
753     {
754       prop = applicationProperties.getProperty(key);
755     }
756     if (prop == null && Platform.isJS())
757     {
758       prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
759               + "_" + JS_PROPERTY_PREFIX + key);
760     }
761     return prop;
762   }
763
764   /**
765    * These methods are used when checking if the saved preference is different
766    * to the default setting
767    */
768
769   public static boolean getDefault(String property, boolean def)
770   {
771     String string = getProperty(property);
772     if (string != null)
773     {
774       def = Boolean.valueOf(string).booleanValue();
775     }
776
777     return def;
778   }
779
780   public static int getDefault(String property, int def)
781   {
782     String string = getProperty(property);
783     if (string != null)
784     {
785       try
786       {
787         def = Integer.parseInt(string);
788       } catch (NumberFormatException e)
789       {
790         if (!Jalview.quiet())
791           jalview.bin.Console.outPrintln("Error parsing int property '"
792                   + property + "' with value '" + string + "'");
793       }
794     }
795
796     return def;
797   }
798
799   /**
800    * Answers the value of the given property, or the supplied default value if
801    * the property is not set
802    */
803   public static String getDefault(String property, String def)
804   {
805     String value = getProperty(property);
806     return value == null ? def : value;
807   }
808
809   /**
810    * Stores property in the file "HOME_DIR/.jalview_properties"
811    * 
812    * @param key
813    *          Name of object
814    * @param obj
815    *          String value of property
816    * 
817    * @return previous value of property (or null)
818    */
819   public static Object setProperty(String key, String obj)
820   {
821     Object oldValue = null;
822     try
823     {
824       oldValue = applicationProperties.setProperty(key, obj);
825       if (propertiesFile != null && !propsAreReadOnly
826       // don't rewrite if new value is same as old value
827               && !((obj == null && oldValue == null)
828                       || (obj != null && obj.equals(oldValue))))
829       {
830         // reset the session property too
831         if (sessionProperties.containsKey(key))
832         {
833           sessionProperties.remove(key);
834         }
835         FileOutputStream out = new FileOutputStream(propertiesFile);
836         applicationProperties.store(out, "---JalviewX Properties File---");
837         out.close();
838       }
839     } catch (Exception ex)
840     {
841       if (!Jalview.quiet())
842         jalview.bin.Console.outPrintln(
843                 "Error setting property: " + key + " " + obj + "\n" + ex);
844     }
845     return oldValue;
846   }
847
848   /**
849    * remove the specified property from the jalview properties file
850    * 
851    * @param string
852    */
853   public static void removeProperty(String string)
854   {
855     applicationProperties.remove(string);
856     saveProperties();
857   }
858
859   /**
860    * save the properties to the jalview properties path
861    */
862   public static void saveProperties()
863   {
864     if (!propsAreReadOnly)
865     {
866       try
867       {
868         FileOutputStream out = new FileOutputStream(propertiesFile);
869         applicationProperties.store(out, "---JalviewX Properties File---");
870         out.close();
871       } catch (Exception ex)
872       {
873         if (!Jalview.quiet())
874           jalview.bin.Console.outPrintln("Error saving properties: " + ex);
875       }
876     }
877   }
878
879   /**
880    * internal vamsas class discovery state
881    */
882   private static int vamsasJarsArePresent = -1;
883
884   /**
885    * Searches for vamsas client classes on class path.
886    * 
887    * @return true if vamsas client is present on classpath
888    */
889   public static boolean vamsasJarsPresent()
890   {
891     if (vamsasJarsArePresent == -1)
892     {
893       try
894       {
895         if (jalview.jbgui.GDesktop.class.getClassLoader()
896                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
897         {
898           Console.debug(
899                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
900           vamsasJarsArePresent = 1;
901           JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
902                   Console.getCachedLogLevel("logs.Vamsas.Level"));
903           JLoggerLog4j.addAppender(lvclient, Console.log,
904                   JALVIEW_LOGGER_NAME);
905           // Tell the user that debug is enabled
906           lvclient.debug(ChannelProperties.getProperty("app_name")
907                   + " Vamsas Client Debugging Output Follows.");
908         }
909       } catch (Exception e)
910       {
911         vamsasJarsArePresent = 0;
912         Console.debug("Vamsas Classes are not present");
913       }
914     }
915     return (vamsasJarsArePresent > 0);
916   }
917
918   /**
919    * internal vamsas class discovery state
920    */
921   private static int groovyJarsArePresent = -1;
922
923   /**
924    * Searches for vamsas client classes on class path.
925    * 
926    * @return true if vamsas client is present on classpath
927    */
928   public static boolean groovyJarsPresent()
929   {
930     if (groovyJarsArePresent == -1)
931     {
932       try
933       {
934         if (Cache.class.getClassLoader()
935                 .loadClass("groovy.lang.GroovyObject") != null)
936         {
937           Console.debug(
938                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
939           groovyJarsArePresent = 1;
940           JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
941                   Console.getCachedLogLevel("logs.Groovy.Level"));
942           JLoggerLog4j.addAppender(lgclient, Console.log,
943                   JALVIEW_LOGGER_NAME);
944           // Tell the user that debug is enabled
945           lgclient.debug(ChannelProperties.getProperty("app_name")
946                   + " Groovy Client Debugging Output Follows.");
947         }
948       } catch (Error e)
949       {
950         groovyJarsArePresent = 0;
951         Console.debug("Groovy Classes are not present", e);
952       } catch (Exception e)
953       {
954         groovyJarsArePresent = 0;
955         Console.debug("Groovy Classes are not present");
956       }
957     }
958     return (groovyJarsArePresent > 0);
959   }
960
961   /**
962    * Initialise the tracker if it is not done already.
963    */
964   public static void initAnalytics()
965   {
966     Plausible.setEnabled(true);
967
968     String appName = ChannelProperties.getProperty("app_name") + " Desktop";
969     String version = Cache.getProperty("VERSION") + "_"
970             + Cache.getDefault("BUILD_DATE", "unknown");
971     String path;
972     /* we don't want to encode ':' as "%3A" for backward compatibility with the UA setup
973     try
974     {
975       path = "/" + String.join("/", URLEncoder.encode(appName, "UTF-8"),
976               URLEncoder.encode(version, "UTF-8"),
977               URLEncoder.encode(APPLICATION_STARTED, "UTF-8"));
978     } catch (UnsupportedEncodingException e)
979     {
980     */
981     List<String> pathParts = new ArrayList<>();
982     pathParts.add(appName);
983     pathParts.add(version);
984     pathParts.add(APPLICATION_STARTED);
985     path = ("/" + String.join("/", pathParts)).replace(' ', '+');
986     /*
987     }
988     */
989     Plausible plausible = Plausible.getInstance();
990
991     // This will send a new "application_launch" event with parameters
992     // including the old-style "path", the channel name and version
993     plausible.sendEvent("application_launch", path, true);
994   }
995
996   private static final String APPLICATION_STARTED = "Application Started";
997
998   /**
999    * get the user's default colour if available
1000    * 
1001    * @param property
1002    * @param defcolour
1003    * @return
1004    */
1005   public static Color getDefaultColour(String property, Color defcolour)
1006   {
1007     String colprop = getProperty(property);
1008     if (colprop == null)
1009     {
1010       return defcolour;
1011     }
1012     Color col = ColorUtils.parseColourString(colprop);
1013     if (col == null)
1014     {
1015       Console.warn("Couldn't parse '" + colprop + "' as a colour for "
1016               + property);
1017     }
1018     return (col == null) ? defcolour : col;
1019   }
1020
1021   /**
1022    * store a colour as a Jalview user default property
1023    * 
1024    * @param property
1025    * @param colour
1026    */
1027   public static void setColourProperty(String property, Color colour)
1028   {
1029     setProperty(property, jalview.util.Format.getHexString(colour));
1030   }
1031
1032   /**
1033    * Stores a formatted date in a jalview property, using a fixed locale.
1034    * 
1035    * @param propertyName
1036    * @param date
1037    * @return the formatted date string
1038    */
1039   public static String setDateProperty(String propertyName, Date date)
1040   {
1041     String formatted = date_format.format(date);
1042     setProperty(propertyName, formatted);
1043     return formatted;
1044   }
1045
1046   /**
1047    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1048    * format) and returns as a Date, or null if parsing fails
1049    * 
1050    * @param propertyName
1051    * @return
1052    * 
1053    */
1054   public static Date getDateProperty(String propertyName)
1055   {
1056     String val = getProperty(propertyName);
1057     if (val != null)
1058     {
1059       try
1060       {
1061         return date_format.parse(val);
1062       } catch (Exception ex)
1063       {
1064         jalview.bin.Console.errPrintln("Invalid or corrupt date in property '"
1065                 + propertyName + "' : value was '" + val + "'");
1066       }
1067     }
1068     return null;
1069   }
1070
1071   /**
1072    * get and parse a property as an integer. send any parsing problems to
1073    * System.err
1074    * 
1075    * @param property
1076    * @return null or Integer
1077    */
1078   public static Integer getIntegerProperty(String property)
1079   {
1080     String val = getProperty(property);
1081     if (val != null && (val = val.trim()).length() > 0)
1082     {
1083       try
1084       {
1085         return Integer.valueOf(val);
1086       } catch (NumberFormatException x)
1087       {
1088         jalview.bin.Console.errPrintln("Invalid integer in property '" + property
1089                 + "' (value was '" + val + "')");
1090       }
1091     }
1092     return null;
1093   }
1094
1095   /**
1096    * Set the specified value, or remove it if null or empty. Does not save the
1097    * properties file.
1098    * 
1099    * @param propName
1100    * @param value
1101    */
1102   public static void setOrRemove(String propName, String value)
1103   {
1104     if (propName == null)
1105     {
1106       return;
1107     }
1108     if (value == null || value.trim().length() < 1)
1109     {
1110       Cache.applicationProperties.remove(propName);
1111     }
1112     else
1113     {
1114       Cache.applicationProperties.setProperty(propName, value);
1115     }
1116   }
1117
1118   /**
1119    * Loads in user colour schemes from files.
1120    * 
1121    * @param files
1122    *          a '|'-delimited list of file paths
1123    */
1124   public static void initUserColourSchemes(String files)
1125   {
1126     if (files == null || files.length() == 0)
1127     {
1128       return;
1129     }
1130
1131     // In case colours can't be loaded, we'll remove them
1132     // from the default list here.
1133     StringBuffer coloursFound = new StringBuffer();
1134     StringTokenizer st = new StringTokenizer(files, "|");
1135     while (st.hasMoreElements())
1136     {
1137       String file = st.nextToken();
1138       try
1139       {
1140         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1141         if (ucs != null)
1142         {
1143           if (coloursFound.length() > 0)
1144           {
1145             coloursFound.append("|");
1146           }
1147           coloursFound.append(file);
1148           ColourSchemes.getInstance().registerColourScheme(ucs);
1149         }
1150       } catch (Exception ex)
1151       {
1152         if (!Jalview.quiet())
1153           jalview.bin.Console
1154                   .outPrintln("Error loading User ColourFile\n" + ex);
1155       }
1156     }
1157     if (!files.equals(coloursFound.toString()))
1158     {
1159       if (coloursFound.toString().length() > 1)
1160       {
1161         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1162                 coloursFound.toString());
1163       }
1164       else
1165       {
1166         applicationProperties
1167                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1168       }
1169     }
1170   }
1171
1172   /**
1173    * Initial logging information helper for various versions output
1174    * 
1175    * @param prefix
1176    * @param value
1177    * @param defaultValue
1178    */
1179   private static void appendIfNotNull(StringBuilder sb, String prefix,
1180           String value, String suffix, String defaultValue)
1181   {
1182     if (value == null && defaultValue == null)
1183     {
1184       return;
1185     }
1186     if (prefix != null)
1187       sb.append(prefix);
1188     sb.append(value == null ? defaultValue : value);
1189     if (suffix != null)
1190       sb.append(suffix);
1191   }
1192
1193   /**
1194    * 
1195    * @return Jalview version, build details and JVM platform version for console
1196    */
1197   public static String getVersionDetailsForConsole()
1198   {
1199     StringBuilder sb = new StringBuilder();
1200     sb.append(ChannelProperties.getProperty("app_name"))
1201             .append(" Version: ");
1202     sb.append(Cache.getDefault("VERSION", "TEST"));
1203     sb.append("\n");
1204     sb.append(ChannelProperties.getProperty("app_name"))
1205             .append(" Installation: ");
1206     sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1207     sb.append("\n");
1208     sb.append("Build Date: ");
1209     sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1210     sb.append("\n");
1211     sb.append("Java version: ");
1212     sb.append(System.getProperty("java.version"));
1213     sb.append("\n");
1214     sb.append("Java platform: ");
1215     sb.append(System.getProperty("os.arch"));
1216     sb.append(" ");
1217     sb.append(System.getProperty("os.name"));
1218     sb.append(" ");
1219     sb.append(System.getProperty("os.version"));
1220     sb.append("\n");
1221     appendIfNotNull(sb, "Install4j version: ",
1222             System.getProperty("sys.install4jVersion"), "\n", null);
1223     appendIfNotNull(sb, "Install4j template version: ",
1224             System.getProperty("installer_template_version"), "\n", null);
1225     appendIfNotNull(sb, "Launcher version: ",
1226             System.getProperty("launcher_version"), "\n", null);
1227     LookAndFeel laf = UIManager.getLookAndFeel();
1228     String lafName = laf == null ? "Not obtained" : laf.getName();
1229     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1230     sb.append("LookAndFeel: ");
1231     sb.append(lafName);
1232     sb.append(" (");
1233     sb.append(lafClass);
1234     sb.append(")\n");
1235     appendIfNotNull(sb, "Channel: ",
1236             ChannelProperties.getProperty("channel"), "\n", null);
1237     if (Console.isDebugEnabled()
1238             || !"release".equals(ChannelProperties.getProperty("channel")))
1239     {
1240       appendIfNotNull(sb, "Getdown appdir: ",
1241               System.getProperty("getdowninstanceappdir"), "\n", null);
1242       appendIfNotNull(sb, "Getdown appbase: ",
1243               System.getProperty("getdowninstanceappbase"), "\n", null);
1244       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1245               "\n", "unknown");
1246       appendIfNotNull(sb, "Preferences file: ", propertiesFile, "\n",
1247               "unknown");
1248     }
1249     return sb.toString();
1250   }
1251
1252   /**
1253    * 
1254    * @return build details as reported in splashscreen
1255    */
1256   public static String getBuildDetailsForSplash()
1257   {
1258     // consider returning more human friendly info
1259     // eg 'built from Source' or update channel
1260     return Cache.getDefault("INSTALLATION", "unknown");
1261   }
1262
1263   public static String getStackTraceString(Throwable t)
1264   {
1265     StringWriter sw = new StringWriter();
1266     PrintWriter pw = new PrintWriter(sw);
1267     t.printStackTrace(pw);
1268     return sw.toString();
1269   }
1270
1271   // proxy properties methods
1272   public static void clearProxyProperties()
1273   {
1274     setProxyProperties(null, null, null, null, null, null, null, null,
1275             null);
1276   }
1277
1278   public static void resetProxyProperties()
1279   {
1280     setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1281             startupProxyProperties[2], startupProxyProperties[3],
1282             startupProxyProperties[4],
1283             startupProxyProperties[5] == null ? null
1284                     : startupProxyProperties[5].toCharArray(),
1285             startupProxyProperties[6],
1286             startupProxyProperties[7] == null ? null
1287                     : startupProxyProperties[7].toCharArray(),
1288             startupProxyProperties[8]);
1289     StringBuilder sb = new StringBuilder();
1290     sb.append("Setting proxy properties to: http.proxyHost=")
1291             .append(startupProxyProperties[0]).append(", http.proxyPort=")
1292             .append(startupProxyProperties[1])
1293             .append(startupProxyProperties[4] != null
1294                     && !startupProxyProperties[4].isEmpty()
1295                             ? " [" + startupProxyProperties[4] + "]"
1296                             : "")
1297             .append(", https.proxyHost=").append(startupProxyProperties[2])
1298             .append(", https.proxyPort=").append(startupProxyProperties[3])
1299             .append(startupProxyProperties[6] != null
1300                     && !startupProxyProperties[6].isEmpty()
1301                             ? " [" + startupProxyProperties[6] + "]"
1302                             : "");
1303
1304     Console.debug(sb.toString());
1305   }
1306
1307   public static void setProxyPropertiesFromPreferences()
1308   {
1309     setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1310   }
1311
1312   public static void setProxyPropertiesFromPreferences(
1313           String previousProxyType)
1314   {
1315     String proxyType = Cache.getDefault("USE_PROXY",
1316             Cache.PROXYTYPE_SYSTEM);
1317     if (previousProxyType != null
1318             && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1319                                                          // customProxy
1320             && proxyType.equals(previousProxyType))
1321     {
1322       // no change
1323       return;
1324     }
1325     switch (proxyType)
1326     {
1327     case Cache.PROXYTYPE_NONE:
1328       if (!previousProxyType.equals(proxyType))
1329       {
1330         Console.info("Setting no proxy settings");
1331         Cache.setProxyProperties(null, null, null, null, null, null, null,
1332                 null, null);
1333       }
1334       break;
1335     case Cache.PROXYTYPE_CUSTOM:
1336       // always re-set a custom proxy -- it might have changed, particularly
1337       // password
1338       Console.info("Setting custom proxy settings");
1339       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1340       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1341               Cache.getDefault("PROXY_PORT", null),
1342               Cache.getDefault("PROXY_SERVER_HTTPS", null),
1343               Cache.getDefault("PROXY_PORT_HTTPS", null),
1344               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1345                       : null,
1346               proxyAuthSet ? Cache.proxyAuthPassword : null,
1347               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1348                       : null,
1349               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1350       break;
1351     default: // system proxy settings by default
1352       Console.info("Setting system proxy settings");
1353       Cache.resetProxyProperties();
1354     }
1355   }
1356
1357   public static void setProxyProperties(String httpHost, String httpPort,
1358           String httpsHost, String httpsPort, String httpUser,
1359           char[] httpPassword, String httpsUser, char[] httpsPassword,
1360           String nonProxyHosts)
1361   {
1362     setOrClearSystemProperty("http.proxyHost", httpHost);
1363     setOrClearSystemProperty("http.proxyPort", httpPort);
1364     setOrClearSystemProperty("https.proxyHost", httpsHost);
1365     setOrClearSystemProperty("https.proxyPort", httpsPort);
1366     setOrClearSystemProperty("http.proxyUser", httpUser);
1367     setOrClearSystemProperty("https.proxyUser", httpsUser);
1368     // note: passwords for http.proxyPassword and https.proxyPassword are sent
1369     // via the Authenticator, properties do not need to be set
1370
1371     // are we using a custom proxy (password prompt might be required)?
1372     boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1373             .equals(PROXYTYPE_CUSTOM);
1374
1375     /*
1376      * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1377      * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1378      * is not re-called).
1379      * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1380      * the AuthCache.
1381      * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1382      * ...
1383      * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1384      */
1385     /*
1386     try
1387     {
1388       sun.net.www.protocol.http.AuthCacheValue
1389               .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1390     } catch (Throwable t)
1391     {
1392       Cache.error(t.getMessage());
1393       Cache.debug(getStackTraceString(t));
1394     }
1395     */
1396
1397     if (httpUser != null || httpsUser != null)
1398     {
1399       try
1400       {
1401         char[] displayHttpPw = new char[httpPassword == null ? 0
1402                 : httpPassword.length];
1403         Arrays.fill(displayHttpPw, '*');
1404         Console.debug(
1405                 "CACHE Proxy: setting new Authenticator with httpUser='"
1406                         + httpUser + "' httpPassword='" + displayHttpPw
1407                         + "'");
1408         if (!Platform.isJS())
1409         /* *
1410          * java.net.Authenticator not implemented in SwingJS yet
1411          * 
1412          * @j2sIgnore
1413          * 
1414          */
1415         {
1416           Authenticator.setDefault(new Authenticator()
1417           {
1418             @Override
1419             protected PasswordAuthentication getPasswordAuthentication()
1420             {
1421               if (getRequestorType() == RequestorType.PROXY)
1422               {
1423                 String protocol = getRequestingProtocol();
1424                 boolean needProxyPasswordSet = false;
1425                 if (customProxySet &&
1426                 // we have a username but no password for the scheme being
1427                 // requested
1428                         (protocol.equalsIgnoreCase("http")
1429                                 && (httpUser != null
1430                                         && httpUser.length() > 0
1431                                         && (httpPassword == null
1432                                                 || httpPassword.length == 0)))
1433                         || (protocol.equalsIgnoreCase("https")
1434                                 && (httpsUser != null
1435                                         && httpsUser.length() > 0
1436                                         && (httpsPassword == null
1437                                                 || httpsPassword.length == 0))))
1438                 {
1439                   // open Preferences -> Connections
1440                   String message = MessageManager
1441                           .getString("label.proxy_password_required");
1442                   Preferences.openPreferences(
1443                           Preferences.TabRef.CONNECTIONS_TAB, message);
1444                   Preferences.getInstance()
1445                           .proxyAuthPasswordCheckHighlight(true, true);
1446                 }
1447                 else
1448                 {
1449                   try
1450                   {
1451                     if (protocol.equalsIgnoreCase("http")
1452                             && getRequestingHost()
1453                                     .equalsIgnoreCase(httpHost)
1454                             && getRequestingPort() == Integer
1455                                     .valueOf(httpPort))
1456                     {
1457                       Console.debug(
1458                               "AUTHENTICATOR returning PasswordAuthentication(\""
1459                                       + httpUser + "\", '"
1460                                       + new String(displayHttpPw) + "')");
1461                       return new PasswordAuthentication(httpUser,
1462                               httpPassword);
1463                     }
1464                     if (protocol.equalsIgnoreCase("https")
1465                             && getRequestingHost()
1466                                     .equalsIgnoreCase(httpsHost)
1467                             && getRequestingPort() == Integer
1468                                     .valueOf(httpsPort))
1469                     {
1470                       char[] displayHttpsPw = new char[httpPassword.length];
1471                       Arrays.fill(displayHttpsPw, '*');
1472                       Console.debug(
1473                               "AUTHENTICATOR returning PasswordAuthentication(\""
1474                                       + httpsUser + "\", '" + displayHttpsPw
1475                                       + "'");
1476                       return new PasswordAuthentication(httpsUser,
1477                               httpsPassword);
1478                     }
1479                   } catch (NumberFormatException e)
1480                   {
1481                     Console.error("Problem with proxy port values [http:"
1482                             + httpPort + ", https:" + httpsPort + "]");
1483                   }
1484                   Console.debug(
1485                           "AUTHENTICATOR after trying to get PasswordAuthentication");
1486                 }
1487               }
1488               // non proxy request
1489               Console.debug("AUTHENTICATOR returning null");
1490               return null;
1491             }
1492           });
1493         } // end of j2sIgnore for java.net.Authenticator
1494
1495         // required to re-enable basic authentication (should be okay for a
1496         // local proxy)
1497         Console.debug(
1498                 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1499         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1500       } catch (SecurityException e)
1501       {
1502         Console.error("Could not set default Authenticator");
1503         Console.debug(getStackTraceString(e));
1504       }
1505     }
1506     else
1507     {
1508       // reset the Authenticator to protect http.proxyUser and
1509       // http.proxyPassword Just In Case
1510       /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1511        * has working credentials. No workaround for Java 11.
1512        */
1513       if (!Platform.isJS())
1514       /* *
1515        * java.net.Authenticator not implemented in SwingJS yet
1516        * 
1517        * @j2sIgnore
1518        * 
1519        */
1520       {
1521         Console.debug(
1522                 "AUTHENTICATOR setting default Authenticator to null");
1523         Authenticator.setDefault(null);
1524       }
1525     }
1526
1527     // nonProxyHosts not currently configurable in Preferences
1528     Console.debug(
1529             "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1530                     + nonProxyHosts + "\"");
1531     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1532   }
1533
1534   public static void setOrClearSystemProperty(String key, char[] value)
1535   {
1536     setOrClearSystemProperty(key,
1537             (value == null) ? null : new String(value));
1538   }
1539
1540   public static void setOrClearSystemProperty(String key, String value)
1541   {
1542     if (key == null)
1543     {
1544       return;
1545     }
1546     if (value == null)
1547     {
1548       System.clearProperty(key);
1549     }
1550     else
1551     {
1552       System.setProperty(key, value);
1553     }
1554   }
1555
1556   /**
1557    * Getdown appbase methods
1558    */
1559
1560   private static final String releaseAppbase;
1561
1562   private static String getdownAppbase;
1563
1564   private static String getdownDistDir;
1565
1566   static
1567   {
1568     if (!Platform.isJS())
1569     {
1570       Float specversion = Float
1571               .parseFloat(System.getProperty("java.specification.version"));
1572       releaseAppbase = (specversion < 9)
1573               ? "https://www.jalview.org/getdown/release/1.8"
1574               : "https://www.jalview.org/getdown/release/11";
1575     }
1576     else
1577     {
1578       // this value currenly made up, can be changed to URL that will be
1579       // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1580       releaseAppbase = "https://www.jalview.org/jalview-js";
1581       getdownAppbase = releaseAppbase;
1582       getdownDistDir = "/swingjs/j2s";
1583     }
1584   }
1585
1586   // look for properties (passed in by getdown) otherwise default to release
1587   private static void setGetdownAppbase()
1588   {
1589     if (getdownAppbase != null)
1590     {
1591       return;
1592     }
1593     String appbase = System.getProperty("getdownappbase");
1594     String distDir = System.getProperty("getdowndistdir");
1595     if (appbase == null)
1596     {
1597       appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1598       distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1599     }
1600     if (appbase == null)
1601     {
1602       appbase = releaseAppbase;
1603       distDir = "release";
1604     }
1605     if (appbase.endsWith("/"))
1606     {
1607       appbase = appbase.substring(0, appbase.length() - 1);
1608     }
1609     if (distDir == null)
1610     {
1611       distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1612     }
1613     getdownAppbase = appbase;
1614     getdownDistDir = distDir;
1615   }
1616
1617   public static String getGetdownAppbase()
1618   {
1619     setGetdownAppbase();
1620     return getdownAppbase;
1621   }
1622
1623   public static String getAppbaseBuildProperties()
1624   {
1625     String appbase = getGetdownAppbase();
1626     return appbase + "/" + getdownDistDir + "/build_properties";
1627   }
1628
1629   private static final Collection<String> bootstrapProperties = new ArrayList<>(
1630           Arrays.asList(JALVIEWLOGLEVEL, BOOTSTRAP_TEST));
1631
1632   public static Properties bootstrapProperties(String filename)
1633   {
1634     Properties bootstrapProps = new Properties();
1635     File file = null;
1636     if (filename != null)
1637     {
1638       file = new File(filename);
1639     }
1640     if (file == null || !file.exists())
1641     {
1642       String channelPrefsFilename = ChannelProperties
1643               .getProperty("preferences.filename");
1644       String propertiesFilename = System.getProperty("user.home")
1645               + File.separatorChar + channelPrefsFilename;
1646       file = new File(propertiesFilename);
1647     }
1648     if (file == null || !file.exists())
1649     {
1650       String releasePrefsFilename = fallbackPropertiesFile;
1651       String releasePropertiesFilename = System.getProperty("user.home")
1652               + File.separatorChar + releasePrefsFilename;
1653       file = new File(releasePropertiesFilename);
1654     }
1655
1656     if (filename == null)
1657       return null;
1658     if (!file.exists())
1659     {
1660       jalview.bin.Console.errPrintln("Could not load bootstrap preferences file '"
1661               + filename + "'");
1662       return null;
1663     }
1664
1665     try
1666     {
1667       FileInputStream in = new FileInputStream(file.getAbsoluteFile());
1668       Properties props = new Properties();
1669       props.load(in);
1670       for (String prop : bootstrapProperties)
1671       {
1672         if (props.containsKey(prop))
1673           bootstrapProps.put(prop, props.getProperty(prop));
1674       }
1675     } catch (FileNotFoundException e)
1676     {
1677       jalview.bin.Console.errPrintln("Could not find bootstrap preferences file '"
1678               + file.getAbsolutePath() + "'");
1679     } catch (IOException e)
1680     {
1681       jalview.bin.Console.errPrintln(
1682               "IOException when loading bootstrap preferences file '"
1683                       + file.getAbsolutePath() + "'");
1684     }
1685     return bootstrapProps;
1686   }
1687
1688   public static void setSessionProperty(String key, String val)
1689   {
1690     if (key != null)
1691     {
1692       sessionProperties.put(key, val);
1693     }
1694   }
1695
1696   public static String getSessionProperty(String key)
1697   {
1698     return key == null ? null : sessionProperties.get(key);
1699   }
1700 }