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