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