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