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