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