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