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