JAL-629 Tidy up tests and replaced methods before merge to develop
[jalview.git] / src / jalview / bin / Cache.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import java.awt.Color;
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.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           if (!Jalview.quiet())
387           {
388             System.out.println(
389                     "Loading jalview properties from : " + propertiesFile);
390             System.out.println(
391                     "Disabling Jalview writing to user's local properties file.");
392           }
393           propsAreReadOnly = true;
394         } catch (Exception ex)
395         {
396           fis = null;
397         }
398         if (fis == null)
399         {
400           String readPropertiesFile = propertiesFile;
401           // if we're using the usual properties file and the channel properties
402           // file doesn't exist, read .jalview_properties
403           // (but we'll still save to the channel properties file).
404           if (defaultProperties && (!new File(propertiesFile).exists())
405                   && (new File(releasePropertiesFile).exists()))
406           {
407             readPropertiesFile = releasePropertiesFile;
408           }
409           fis = new FileInputStream(readPropertiesFile);
410         }
411         applicationProperties.clear();
412         applicationProperties.load(fis);
413
414         // remove any old build properties
415
416         deleteBuildProperties();
417         fis.close();
418       } catch (Exception ex)
419       {
420         if (!Jalview.quiet())
421           System.out.println("Error reading properties file: " + ex);
422       }
423     }
424
425     /* TO BE REPLACED WITH PROXY_TYPE SETTINGS 
426     if (getDefault("USE_PROXY", false))
427     {
428       String proxyServer = getDefault("PROXY_SERVER", ""),
429               proxyPort = getDefault("PROXY_PORT", "8080");
430     }
431     */
432
433     // PROXY TYPE settings (now three options "none", "false", "true", but using
434     // backward compatible strings)
435     String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
436     // default to upgrading old settings
437     switch (proxyType)
438     {
439     case PROXYTYPE_NONE:
440       clearProxyProperties();
441       break;
442     case PROXYTYPE_SYSTEM: // use system settings
443       resetProxyProperties();
444       break;
445     case PROXYTYPE_CUSTOM: // use specified proxy settings
446       String httpHost = getDefault("PROXY_SERVER", "");
447       String httpPort = getDefault("PROXY_PORT", "8080");
448       String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
449       String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
450       String httpUser = getDefault("PROXY_AUTH_USER", null);
451       // https.proxyUser and https.proxyPassword are not able to be
452       // independently set in Preferences yet (or http.nonProxyHosts)
453       String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
454       setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
455               proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
456       break;
457     default:
458       String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
459               + proxyType;
460       Console.warn(message);
461     }
462
463     // LOAD THE AUTHORS FROM THE authors.props file
464     String authorDetails = resolveResourceURLFor("/authors.props");
465
466     try
467     {
468       if (authorDetails != null)
469       {
470         URL localJarFileURL = new URL(authorDetails);
471         InputStream in = localJarFileURL.openStream();
472         applicationProperties.load(in);
473         in.close();
474       }
475     } catch (Exception ex)
476     {
477       if (!Jalview.quiet())
478         System.out.println("Error reading author details: " + ex);
479       authorDetails = null;
480     }
481     if (authorDetails == null)
482     {
483       applicationProperties.remove("AUTHORS");
484       applicationProperties.remove("AUTHORFNAMES");
485       applicationProperties.remove("YEAR");
486     }
487
488     loadBuildProperties(false);
489
490     SiftsSettings
491             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
492
493     SiftsSettings.setSiftDownloadDirectory(Cache
494             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
495
496     SiftsSettings.setFailSafePIDThreshold(
497             Cache.getDefault("sifts_fail_safe_pid_threshold",
498                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
499
500     SiftsSettings.setCacheThresholdInDays(
501             Cache.getDefault("sifts_cache_threshold_in_days",
502                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
503
504     IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
505             "https://www.jalview.org/services/identifiers"));
506     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
507
508     StructureImportSettings.setDefaultStructureFileFormat(
509             Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
510     StructureImportSettings
511             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
512     // StructureImportSettings
513     // .setDefaultPDBFileParser(Cache.getDefault(
514     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
515
516     String jnlpVersion = System.getProperty("jalview.version");
517
518     // jnlpVersion will be null if a latest version check for the channel needs
519     // to be done
520     // Dont do this check if running in headless mode
521
522     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
523             && (System.getProperty("java.awt.headless") == null || System
524                     .getProperty("java.awt.headless").equals("false")))
525     {
526
527       class VersionChecker extends Thread
528       {
529
530         @Override
531         public void run()
532         {
533           String remoteBuildPropertiesUrl = Cache
534                   .getAppbaseBuildProperties();
535
536           String orgtimeout = System
537                   .getProperty("sun.net.client.defaultConnectTimeout");
538           if (orgtimeout == null)
539           {
540             orgtimeout = "30";
541             Console.debug("Setting default net timeout to " + orgtimeout
542                     + " seconds.");
543           }
544           String remoteVersion = null;
545           if (remoteBuildPropertiesUrl.startsWith("http"))
546           {
547             try
548             {
549               System.setProperty("sun.net.client.defaultConnectTimeout",
550                       "5000");
551
552               URL url = new URL(remoteBuildPropertiesUrl);
553
554               BufferedReader in = new BufferedReader(
555                       new InputStreamReader(url.openStream()));
556
557               Properties remoteBuildProperties = new Properties();
558               remoteBuildProperties.load(in);
559               remoteVersion = remoteBuildProperties.getProperty("VERSION");
560             } catch (Exception ex)
561             {
562               if (!Jalview.quiet())
563               {
564                 System.out.println(
565                         "Non-fatal exception when checking version at "
566                                 + remoteBuildPropertiesUrl + ":");
567                 System.out.println(ex);
568               }
569               remoteVersion = getProperty("VERSION");
570             }
571           }
572           System.setProperty("sun.net.client.defaultConnectTimeout",
573                   orgtimeout);
574
575           setProperty("LATEST_VERSION", remoteVersion);
576         }
577       }
578
579       VersionChecker vc = new VersionChecker();
580       vc.start();
581     }
582     else
583     {
584       if (jnlpVersion != null)
585       {
586         setProperty("LATEST_VERSION", jnlpVersion);
587       }
588       else
589       {
590         applicationProperties.remove("LATEST_VERSION");
591       }
592     }
593
594     // LOAD USERDEFINED COLOURS
595     Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
596     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
597             false);
598   }
599
600   /**
601    * construct a resource URL for the given absolute resource pathname
602    * 
603    * @param resourcePath
604    * @return
605    */
606   private static String resolveResourceURLFor(String resourcePath)
607   {
608     String url = null;
609     if (Platform.isJS() || !Cache.class.getProtectionDomain()
610             .getCodeSource().getLocation().toString().endsWith(".jar"))
611     {
612       try
613       {
614         url = Cache.class.getResource(resourcePath).toString();
615       } catch (Exception ex)
616       {
617         System.err.println("Failed to resolve resource " + resourcePath
618                 + ": " + ex.getMessage());
619       }
620     }
621     else
622     {
623       url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
624               .getLocation().toString().concat("!" + resourcePath));
625     }
626     return url;
627   }
628
629   public static void loadBuildProperties(boolean reportVersion)
630   {
631     String codeInstallation = getProperty("INSTALLATION");
632     boolean printVersion = codeInstallation == null;
633
634     /*
635      * read build properties - from the Jalview jar for a Java distribution,
636      * or from codebase file in test or JalviewJS context
637      */
638     try
639     {
640       String buildDetails = resolveResourceURLFor("/.build_properties");
641       URL localJarFileURL = new URL(buildDetails);
642       InputStream in = localJarFileURL.openStream();
643       buildProperties.load(in);
644       in.close();
645       if (buildProperties.getProperty("BUILD_DATE", null) != null)
646       {
647         applicationProperties.put("BUILD_DATE",
648                 buildProperties.getProperty("BUILD_DATE"));
649       }
650       if (buildProperties.getProperty("INSTALLATION", null) != null)
651       {
652         applicationProperties.put("INSTALLATION",
653                 buildProperties.getProperty("INSTALLATION"));
654       }
655       if (buildProperties.getProperty("VERSION", null) != null)
656       {
657         applicationProperties.put("VERSION",
658                 buildProperties.getProperty("VERSION"));
659       }
660       if (buildProperties.getProperty("JAVA_COMPILE_VERSION", null) != null)
661       {
662         applicationProperties.put("JAVA_COMPILE_VERSION",
663                 buildProperties.getProperty("JAVA_COMPILE_VERSION"));
664       }
665     } catch (Exception ex)
666     {
667       if (!Jalview.quiet())
668         System.out.println("Error reading build details: " + ex);
669       applicationProperties.remove("VERSION");
670     }
671     String codeVersion = getProperty("VERSION");
672     codeInstallation = getProperty("INSTALLATION");
673
674     if (codeVersion == null)
675     {
676       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
677       codeVersion = "Test";
678       codeInstallation = "";
679     }
680     else
681     {
682       codeInstallation = " (" + codeInstallation + ")";
683     }
684     setProperty("VERSION", codeVersion);
685     new BuildDetails(codeVersion, null, codeInstallation);
686     if (printVersion && reportVersion)
687     {
688       System.out.println(ChannelProperties.getProperty("app_name")
689               + " version: " + codeVersion + codeInstallation);
690     }
691   }
692
693   private static void deleteBuildProperties()
694   {
695     applicationProperties.remove("LATEST_VERSION");
696     applicationProperties.remove("VERSION");
697     applicationProperties.remove("AUTHORS");
698     applicationProperties.remove("AUTHORFNAMES");
699     applicationProperties.remove("YEAR");
700     applicationProperties.remove("BUILD_DATE");
701     applicationProperties.remove("INSTALLATION");
702   }
703
704   /**
705    * Gets Jalview application property of given key. Returns null if key not
706    * found
707    * 
708    * @param key
709    *          Name of property
710    * 
711    * @return Property value
712    */
713   public static String getProperty(String key)
714   {
715     String prop = applicationProperties.getProperty(key);
716     if (prop == null && Platform.isJS())
717     {
718       prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
719               + "_" + JS_PROPERTY_PREFIX + key);
720     }
721     return prop;
722   }
723
724   /**
725    * These methods are used when checking if the saved preference is different
726    * to the default setting
727    */
728
729   public static boolean getDefault(String property, boolean def)
730   {
731     String string = getProperty(property);
732     if (string != null)
733     {
734       def = Boolean.valueOf(string).booleanValue();
735     }
736
737     return def;
738   }
739
740   public static int getDefault(String property, int def)
741   {
742     String string = getProperty(property);
743     if (string != null)
744     {
745       try
746       {
747         def = Integer.parseInt(string);
748       } catch (NumberFormatException e)
749       {
750         if (!Jalview.quiet())
751           System.out.println("Error parsing int property '" + property
752                   + "' with value '" + string + "'");
753       }
754     }
755
756     return def;
757   }
758
759   /**
760    * Answers the value of the given property, or the supplied default value if
761    * the property is not set
762    */
763   public static String getDefault(String property, String def)
764   {
765     String value = getProperty(property);
766     return value == null ? def : value;
767   }
768
769   /**
770    * Stores property in the file "HOME_DIR/.jalview_properties"
771    * 
772    * @param key
773    *          Name of object
774    * @param obj
775    *          String value of property
776    * 
777    * @return previous value of property (or null)
778    */
779   public static Object setProperty(String key, String obj)
780   {
781     Object oldValue = null;
782     try
783     {
784       oldValue = applicationProperties.setProperty(key, obj);
785       if (propertiesFile != null && !propsAreReadOnly)
786       {
787         FileOutputStream out = new FileOutputStream(propertiesFile);
788         applicationProperties.store(out, "---JalviewX Properties File---");
789         out.close();
790       }
791     } catch (Exception ex)
792     {
793       if (!Jalview.quiet())
794         System.out.println(
795                 "Error setting property: " + key + " " + obj + "\n" + ex);
796     }
797     return oldValue;
798   }
799
800   /**
801    * remove the specified property from the jalview properties file
802    * 
803    * @param string
804    */
805   public static void removeProperty(String string)
806   {
807     applicationProperties.remove(string);
808     saveProperties();
809   }
810
811   /**
812    * save the properties to the jalview properties path
813    */
814   public static void saveProperties()
815   {
816     if (!propsAreReadOnly)
817     {
818       try
819       {
820         FileOutputStream out = new FileOutputStream(propertiesFile);
821         applicationProperties.store(out, "---JalviewX Properties File---");
822         out.close();
823       } catch (Exception ex)
824       {
825         if (!Jalview.quiet())
826           System.out.println("Error saving properties: " + ex);
827       }
828     }
829   }
830
831   /**
832    * internal vamsas class discovery state
833    */
834   private static int vamsasJarsArePresent = -1;
835
836   /**
837    * Searches for vamsas client classes on class path.
838    * 
839    * @return true if vamsas client is present on classpath
840    */
841   public static boolean vamsasJarsPresent()
842   {
843     if (vamsasJarsArePresent == -1)
844     {
845       try
846       {
847         if (jalview.jbgui.GDesktop.class.getClassLoader()
848                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
849         {
850           Console.debug(
851                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
852           vamsasJarsArePresent = 1;
853           JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
854                   Console.getCachedLogLevel("logs.Vamsas.Level"));
855           JLoggerLog4j.addAppender(lvclient, Console.log,
856                   JALVIEW_LOGGER_NAME);
857           // Tell the user that debug is enabled
858           lvclient.debug(ChannelProperties.getProperty("app_name")
859                   + " Vamsas Client Debugging Output Follows.");
860         }
861       } catch (Exception e)
862       {
863         vamsasJarsArePresent = 0;
864         Console.debug("Vamsas Classes are not present");
865       }
866     }
867     return (vamsasJarsArePresent > 0);
868   }
869
870   /**
871    * internal vamsas class discovery state
872    */
873   private static int groovyJarsArePresent = -1;
874
875   /**
876    * Searches for vamsas client classes on class path.
877    * 
878    * @return true if vamsas client is present on classpath
879    */
880   public static boolean groovyJarsPresent()
881   {
882     if (groovyJarsArePresent == -1)
883     {
884       try
885       {
886         if (Cache.class.getClassLoader()
887                 .loadClass("groovy.lang.GroovyObject") != null)
888         {
889           Console.debug(
890                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
891           groovyJarsArePresent = 1;
892           JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
893                   Console.getCachedLogLevel("logs.Groovy.Level"));
894           JLoggerLog4j.addAppender(lgclient, Console.log,
895                   JALVIEW_LOGGER_NAME);
896           // Tell the user that debug is enabled
897           lgclient.debug(ChannelProperties.getProperty("app_name")
898                   + " Groovy Client Debugging Output Follows.");
899         }
900       } catch (Error e)
901       {
902         groovyJarsArePresent = 0;
903         Console.debug("Groovy Classes are not present", e);
904       } catch (Exception e)
905       {
906         groovyJarsArePresent = 0;
907         Console.debug("Groovy Classes are not present");
908       }
909     }
910     return (groovyJarsArePresent > 0);
911   }
912
913   /**
914    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
915    * enabled.
916    */
917   protected static Object tracker = null;
918
919   protected static Class trackerfocus = null;
920
921   protected static Class jgoogleanalyticstracker = null;
922
923   /**
924    * Initialise the google tracker if it is not done already.
925    */
926   public static void initGoogleTracker()
927   {
928     if (tracker == null)
929     {
930       if (jgoogleanalyticstracker == null)
931       {
932         // try to get the tracker class
933         try
934         {
935           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
936                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
937           trackerfocus = Cache.class.getClassLoader()
938                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
939         } catch (Exception e)
940         {
941           Console.debug(
942                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
943           tracker = null;
944           jgoogleanalyticstracker = null;
945           trackerfocus = null;
946           return;
947         }
948       }
949       // now initialise tracker
950       Exception re = null, ex = null;
951       Error err = null;
952       String vrs = "No Version Accessible";
953       try
954       {
955         // Google analytics tracking code for Library Finder
956         tracker = jgoogleanalyticstracker
957                 .getConstructor(new Class[]
958                 { String.class, String.class, String.class })
959                 .newInstance(new Object[]
960                 { ChannelProperties.getProperty("app_name") + " Desktop",
961                     (vrs = Cache.getProperty("VERSION") + "_"
962                             + Cache.getDefault("BUILD_DATE", "unknown")),
963                     "UA-9060947-1" });
964         jgoogleanalyticstracker
965                 .getMethod("trackAsynchronously", new Class[]
966                 { trackerfocus })
967                 .invoke(tracker, new Object[]
968                 { trackerfocus.getConstructor(new Class[] { String.class })
969                         .newInstance(new Object[]
970                         { "Application Started." }) });
971       } catch (RuntimeException e)
972       {
973         re = e;
974       } catch (Exception e)
975       {
976         ex = e;
977       } catch (Error e)
978       {
979         err = e;
980       }
981       if (re != null || ex != null || err != null)
982       {
983         if (re != null)
984         {
985           Console.debug("Caught runtime exception in googletracker init:",
986                   re);
987         }
988         if (ex != null)
989         {
990           Console.warn(
991                   "Failed to initialise GoogleTracker for Jalview Desktop with version "
992                           + vrs,
993                   ex);
994         }
995         if (err != null)
996         {
997           Console.error(
998                   "Whilst initing GoogleTracker for Jalview Desktop version "
999                           + vrs,
1000                   err);
1001         }
1002       }
1003       else
1004       {
1005         Console.debug("Successfully initialised tracker.");
1006       }
1007     }
1008   }
1009
1010   /**
1011    * get the user's default colour if available
1012    * 
1013    * @param property
1014    * @param defcolour
1015    * @return
1016    */
1017   public static Color getDefaultColour(String property, Color defcolour)
1018   {
1019     String colprop = getProperty(property);
1020     if (colprop == null)
1021     {
1022       return defcolour;
1023     }
1024     Color col = ColorUtils.parseColourString(colprop);
1025     if (col == null)
1026     {
1027       Console.warn("Couldn't parse '" + colprop + "' as a colour for "
1028               + property);
1029     }
1030     return (col == null) ? defcolour : col;
1031   }
1032
1033   /**
1034    * store a colour as a Jalview user default property
1035    * 
1036    * @param property
1037    * @param colour
1038    */
1039   public static void setColourProperty(String property, Color colour)
1040   {
1041     setProperty(property, jalview.util.Format.getHexString(colour));
1042   }
1043
1044   /**
1045    * Stores a formatted date in a jalview property, using a fixed locale.
1046    * 
1047    * @param propertyName
1048    * @param date
1049    * @return the formatted date string
1050    */
1051   public static String setDateProperty(String propertyName, Date date)
1052   {
1053     String formatted = date_format.format(date);
1054     setProperty(propertyName, formatted);
1055     return formatted;
1056   }
1057
1058   /**
1059    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1060    * format) and returns as a Date, or null if parsing fails
1061    * 
1062    * @param propertyName
1063    * @return
1064    * 
1065    */
1066   public static Date getDateProperty(String propertyName)
1067   {
1068     String val = getProperty(propertyName);
1069     if (val != null)
1070     {
1071       try
1072       {
1073         return date_format.parse(val);
1074       } catch (Exception ex)
1075       {
1076         System.err.println("Invalid or corrupt date in property '"
1077                 + propertyName + "' : value was '" + val + "'");
1078       }
1079     }
1080     return null;
1081   }
1082
1083   /**
1084    * get and parse a property as an integer. send any parsing problems to
1085    * System.err
1086    * 
1087    * @param property
1088    * @return null or Integer
1089    */
1090   public static Integer getIntegerProperty(String property)
1091   {
1092     String val = getProperty(property);
1093     if (val != null && (val = val.trim()).length() > 0)
1094     {
1095       try
1096       {
1097         return Integer.valueOf(val);
1098       } catch (NumberFormatException x)
1099       {
1100         System.err.println("Invalid integer in property '" + property
1101                 + "' (value was '" + val + "')");
1102       }
1103     }
1104     return null;
1105   }
1106
1107   /**
1108    * Set the specified value, or remove it if null or empty. Does not save the
1109    * properties file.
1110    * 
1111    * @param propName
1112    * @param value
1113    */
1114   public static void setOrRemove(String propName, String value)
1115   {
1116     if (propName == null)
1117     {
1118       return;
1119     }
1120     if (value == null || value.trim().length() < 1)
1121     {
1122       Cache.applicationProperties.remove(propName);
1123     }
1124     else
1125     {
1126       Cache.applicationProperties.setProperty(propName, value);
1127     }
1128   }
1129
1130   /**
1131    * Loads in user colour schemes from files.
1132    * 
1133    * @param files
1134    *          a '|'-delimited list of file paths
1135    */
1136   public static void initUserColourSchemes(String files)
1137   {
1138     if (files == null || files.length() == 0)
1139     {
1140       return;
1141     }
1142
1143     // In case colours can't be loaded, we'll remove them
1144     // from the default list here.
1145     StringBuffer coloursFound = new StringBuffer();
1146     StringTokenizer st = new StringTokenizer(files, "|");
1147     while (st.hasMoreElements())
1148     {
1149       String file = st.nextToken();
1150       try
1151       {
1152         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1153         if (ucs != null)
1154         {
1155           if (coloursFound.length() > 0)
1156           {
1157             coloursFound.append("|");
1158           }
1159           coloursFound.append(file);
1160           ColourSchemes.getInstance().registerColourScheme(ucs);
1161         }
1162       } catch (Exception ex)
1163       {
1164         if (!Jalview.quiet())
1165           System.out.println("Error loading User ColourFile\n" + ex);
1166       }
1167     }
1168     if (!files.equals(coloursFound.toString()))
1169     {
1170       if (coloursFound.toString().length() > 1)
1171       {
1172         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1173                 coloursFound.toString());
1174       }
1175       else
1176       {
1177         applicationProperties
1178                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1179       }
1180     }
1181   }
1182
1183   /**
1184    * Initial logging information helper for various versions output
1185    * 
1186    * @param prefix
1187    * @param value
1188    * @param defaultValue
1189    */
1190   private static void appendIfNotNull(StringBuilder sb, String prefix,
1191           String value, String suffix, String defaultValue)
1192   {
1193     if (value == null && defaultValue == null)
1194     {
1195       return;
1196     }
1197     if (prefix != null)
1198       sb.append(prefix);
1199     sb.append(value == null ? defaultValue : value);
1200     if (suffix != null)
1201       sb.append(suffix);
1202   }
1203
1204   /**
1205    * 
1206    * @return Jalview version, build details and JVM platform version for console
1207    */
1208   public static String getVersionDetailsForConsole()
1209   {
1210     StringBuilder sb = new StringBuilder();
1211     sb.append(ChannelProperties.getProperty("app_name"))
1212             .append(" Version: ");
1213     sb.append(Cache.getDefault("VERSION", "TEST"));
1214     sb.append("\n");
1215     sb.append(ChannelProperties.getProperty("app_name"))
1216             .append(" Installation: ");
1217     sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1218     sb.append("\n");
1219     sb.append("Build Date: ");
1220     sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1221     sb.append("\n");
1222     sb.append("Java version: ");
1223     sb.append(System.getProperty("java.version"));
1224     sb.append("\n");
1225     sb.append("Java platform: ");
1226     sb.append(System.getProperty("os.arch"));
1227     sb.append(" ");
1228     sb.append(System.getProperty("os.name"));
1229     sb.append(" ");
1230     sb.append(System.getProperty("os.version"));
1231     sb.append("\n");
1232     appendIfNotNull(sb, "Install4j version: ",
1233             System.getProperty("sys.install4jVersion"), "\n", null);
1234     appendIfNotNull(sb, "Install4j template version: ",
1235             System.getProperty("installer_template_version"), "\n", null);
1236     appendIfNotNull(sb, "Launcher version: ",
1237             System.getProperty("launcher_version"), "\n", null);
1238     LookAndFeel laf = UIManager.getLookAndFeel();
1239     String lafName = laf == null ? "Not obtained" : laf.getName();
1240     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1241     sb.append("LookAndFeel: ");
1242     sb.append(lafName);
1243     sb.append(" (");
1244     sb.append(lafClass);
1245     sb.append(")\n");
1246     appendIfNotNull(sb, "Channel: ",
1247             ChannelProperties.getProperty("channel"), "\n", null);
1248     if (Console.isDebugEnabled()
1249             || !"release".equals(ChannelProperties.getProperty("channel")))
1250     {
1251       appendIfNotNull(sb, "Getdown appdir: ",
1252               System.getProperty("getdowninstanceappdir"), "\n", null);
1253       appendIfNotNull(sb, "Getdown appbase: ",
1254               System.getProperty("getdowninstanceappbase"), "\n", null);
1255       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1256               "\n", "unknown");
1257       appendIfNotNull(sb, "Preferences file: ", propertiesFile, "\n",
1258               "unknown");
1259     }
1260     return sb.toString();
1261   }
1262
1263   /**
1264    * 
1265    * @return build details as reported in splashscreen
1266    */
1267   public static String getBuildDetailsForSplash()
1268   {
1269     // consider returning more human friendly info
1270     // eg 'built from Source' or update channel
1271     return Cache.getDefault("INSTALLATION", "unknown");
1272   }
1273
1274   public static String getStackTraceString(Throwable t)
1275   {
1276     StringWriter sw = new StringWriter();
1277     PrintWriter pw = new PrintWriter(sw);
1278     t.printStackTrace(pw);
1279     return sw.toString();
1280   }
1281
1282   // proxy properties methods
1283   public static void clearProxyProperties()
1284   {
1285     setProxyProperties(null, null, null, null, null, null, null, null,
1286             null);
1287   }
1288
1289   public static void resetProxyProperties()
1290   {
1291     setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1292             startupProxyProperties[2], startupProxyProperties[3],
1293             startupProxyProperties[4],
1294             startupProxyProperties[5] == null ? null
1295                     : startupProxyProperties[5].toCharArray(),
1296             startupProxyProperties[6],
1297             startupProxyProperties[7] == null ? null
1298                     : startupProxyProperties[7].toCharArray(),
1299             startupProxyProperties[8]);
1300     StringBuilder sb = new StringBuilder();
1301     sb.append("Setting proxy properties to: http.proxyHost=")
1302             .append(startupProxyProperties[0]).append(", http.proxyPort=")
1303             .append(startupProxyProperties[1])
1304             .append(startupProxyProperties[4] != null
1305                     && !startupProxyProperties[4].isEmpty()
1306                             ? " [" + startupProxyProperties[4] + "]"
1307                             : "")
1308             .append(", https.proxyHost=").append(startupProxyProperties[2])
1309             .append(", https.proxyPort=").append(startupProxyProperties[3])
1310             .append(startupProxyProperties[6] != null
1311                     && !startupProxyProperties[6].isEmpty()
1312                             ? " [" + startupProxyProperties[6] + "]"
1313                             : "");
1314
1315     Console.debug(sb.toString());
1316   }
1317
1318   public static void setProxyPropertiesFromPreferences()
1319   {
1320     setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1321   }
1322
1323   public static void setProxyPropertiesFromPreferences(
1324           String previousProxyType)
1325   {
1326     String proxyType = Cache.getDefault("USE_PROXY",
1327             Cache.PROXYTYPE_SYSTEM);
1328     if (previousProxyType != null
1329             && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1330                                                          // customProxy
1331             && proxyType.equals(previousProxyType))
1332     {
1333       // no change
1334       return;
1335     }
1336     switch (proxyType)
1337     {
1338     case Cache.PROXYTYPE_NONE:
1339       if (!previousProxyType.equals(proxyType))
1340       {
1341         Console.info("Setting no proxy settings");
1342         Cache.setProxyProperties(null, null, null, null, null, null, null,
1343                 null, null);
1344       }
1345       break;
1346     case Cache.PROXYTYPE_CUSTOM:
1347       // always re-set a custom proxy -- it might have changed, particularly
1348       // password
1349       Console.info("Setting custom proxy settings");
1350       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1351       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1352               Cache.getDefault("PROXY_PORT", null),
1353               Cache.getDefault("PROXY_SERVER_HTTPS", null),
1354               Cache.getDefault("PROXY_PORT_HTTPS", null),
1355               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1356                       : null,
1357               proxyAuthSet ? Cache.proxyAuthPassword : null,
1358               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1359                       : null,
1360               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1361       break;
1362     default: // system proxy settings by default
1363       Console.info("Setting system proxy settings");
1364       Cache.resetProxyProperties();
1365     }
1366   }
1367
1368   public static void setProxyProperties(String httpHost, String httpPort,
1369           String httpsHost, String httpsPort, String httpUser,
1370           char[] httpPassword, String httpsUser, char[] httpsPassword,
1371           String nonProxyHosts)
1372   {
1373     setOrClearSystemProperty("http.proxyHost", httpHost);
1374     setOrClearSystemProperty("http.proxyPort", httpPort);
1375     setOrClearSystemProperty("https.proxyHost", httpsHost);
1376     setOrClearSystemProperty("https.proxyPort", httpsPort);
1377     setOrClearSystemProperty("http.proxyUser", httpUser);
1378     setOrClearSystemProperty("https.proxyUser", httpsUser);
1379     // note: passwords for http.proxyPassword and https.proxyPassword are sent
1380     // via the Authenticator, properties do not need to be set
1381
1382     // are we using a custom proxy (password prompt might be required)?
1383     boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1384             .equals(PROXYTYPE_CUSTOM);
1385
1386     /*
1387      * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1388      * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1389      * is not re-called).
1390      * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1391      * the AuthCache.
1392      * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1393      * ...
1394      * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1395      */
1396     /*
1397     try
1398     {
1399       sun.net.www.protocol.http.AuthCacheValue
1400               .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1401     } catch (Throwable t)
1402     {
1403       Cache.error(t.getMessage());
1404       Cache.debug(getStackTraceString(t));
1405     }
1406     */
1407
1408     if (httpUser != null || httpsUser != null)
1409     {
1410       try
1411       {
1412         char[] displayHttpPw = new char[httpPassword == null ? 0
1413                 : httpPassword.length];
1414         Arrays.fill(displayHttpPw, '*');
1415         Console.debug(
1416                 "CACHE Proxy: setting new Authenticator with httpUser='"
1417                         + httpUser + "' httpPassword='" + displayHttpPw
1418                         + "'");
1419         if (!Platform.isJS())
1420         /* *
1421          * java.net.Authenticator not implemented in SwingJS yet
1422          * 
1423          * @j2sIgnore
1424          * 
1425          */
1426         {
1427           Authenticator.setDefault(new Authenticator()
1428           {
1429             @Override
1430             protected PasswordAuthentication getPasswordAuthentication()
1431             {
1432               if (getRequestorType() == RequestorType.PROXY)
1433               {
1434                 String protocol = getRequestingProtocol();
1435                 boolean needProxyPasswordSet = false;
1436                 if (customProxySet &&
1437                 // we have a username but no password for the scheme being
1438                 // requested
1439                         (protocol.equalsIgnoreCase("http")
1440                                 && (httpUser != null
1441                                         && httpUser.length() > 0
1442                                         && (httpPassword == null
1443                                                 || httpPassword.length == 0)))
1444                         || (protocol.equalsIgnoreCase("https")
1445                                 && (httpsUser != null
1446                                         && httpsUser.length() > 0
1447                                         && (httpsPassword == null
1448                                                 || httpsPassword.length == 0))))
1449                 {
1450                   // open Preferences -> Connections
1451                   String message = MessageManager
1452                           .getString("label.proxy_password_required");
1453                   Preferences.openPreferences(
1454                           Preferences.TabRef.CONNECTIONS_TAB, message);
1455                   Preferences.getInstance()
1456                           .proxyAuthPasswordCheckHighlight(true, true);
1457                 }
1458                 else
1459                 {
1460                   try
1461                   {
1462                     if (protocol.equalsIgnoreCase("http")
1463                             && getRequestingHost()
1464                                     .equalsIgnoreCase(httpHost)
1465                             && getRequestingPort() == Integer
1466                                     .valueOf(httpPort))
1467                     {
1468                       Console.debug(
1469                               "AUTHENTICATOR returning PasswordAuthentication(\""
1470                                       + httpUser + "\", '"
1471                                       + new String(displayHttpPw) + "')");
1472                       return new PasswordAuthentication(httpUser,
1473                               httpPassword);
1474                     }
1475                     if (protocol.equalsIgnoreCase("https")
1476                             && getRequestingHost()
1477                                     .equalsIgnoreCase(httpsHost)
1478                             && getRequestingPort() == Integer
1479                                     .valueOf(httpsPort))
1480                     {
1481                       char[] displayHttpsPw = new char[httpPassword.length];
1482                       Arrays.fill(displayHttpsPw, '*');
1483                       Console.debug(
1484                               "AUTHENTICATOR returning PasswordAuthentication(\""
1485                                       + httpsUser + "\", '" + displayHttpsPw
1486                                       + "'");
1487                       return new PasswordAuthentication(httpsUser,
1488                               httpsPassword);
1489                     }
1490                   } catch (NumberFormatException e)
1491                   {
1492                     Console.error("Problem with proxy port values [http:"
1493                             + httpPort + ", https:" + httpsPort + "]");
1494                   }
1495                   Console.debug(
1496                           "AUTHENTICATOR after trying to get PasswordAuthentication");
1497                 }
1498               }
1499               // non proxy request
1500               Console.debug("AUTHENTICATOR returning null");
1501               return null;
1502             }
1503           });
1504         } // end of j2sIgnore for java.net.Authenticator
1505
1506         // required to re-enable basic authentication (should be okay for a
1507         // local proxy)
1508         Console.debug(
1509                 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1510         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1511       } catch (SecurityException e)
1512       {
1513         Console.error("Could not set default Authenticator");
1514         Console.debug(getStackTraceString(e));
1515       }
1516     }
1517     else
1518     {
1519       // reset the Authenticator to protect http.proxyUser and
1520       // http.proxyPassword Just In Case
1521       /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1522        * has working credentials. No workaround for Java 11.
1523        */
1524       if (!Platform.isJS())
1525       /* *
1526        * java.net.Authenticator not implemented in SwingJS yet
1527        * 
1528        * @j2sIgnore
1529        * 
1530        */
1531       {
1532         Console.debug(
1533                 "AUTHENTICATOR setting default Authenticator to null");
1534         Authenticator.setDefault(null);
1535       }
1536     }
1537
1538     // nonProxyHosts not currently configurable in Preferences
1539     Console.debug(
1540             "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1541                     + nonProxyHosts + "\"");
1542     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1543   }
1544
1545   public static void setOrClearSystemProperty(String key, char[] value)
1546   {
1547     setOrClearSystemProperty(key,
1548             (value == null) ? null : new String(value));
1549   }
1550
1551   public static void setOrClearSystemProperty(String key, String value)
1552   {
1553     if (key == null)
1554     {
1555       return;
1556     }
1557     if (value == null)
1558     {
1559       System.clearProperty(key);
1560     }
1561     else
1562     {
1563       System.setProperty(key, value);
1564     }
1565   }
1566
1567   /**
1568    * Getdown appbase methods
1569    */
1570
1571   private static final String releaseAppbase;
1572
1573   private static String getdownAppbase;
1574
1575   private static String getdownDistDir;
1576
1577   static
1578   {
1579     if (!Platform.isJS())
1580     {
1581       Float specversion = Float
1582               .parseFloat(System.getProperty("java.specification.version"));
1583       releaseAppbase = (specversion < 9)
1584               ? "https://www.jalview.org/getdown/release/1.8"
1585               : "https://www.jalview.org/getdown/release/11";
1586     }
1587     else
1588     {
1589       // this value currenly made up, can be changed to URL that will be
1590       // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1591       releaseAppbase = "https://www.jalview.org/jalview-js";
1592       getdownAppbase = releaseAppbase;
1593       getdownDistDir = "/swingjs/j2s";
1594     }
1595   }
1596
1597   // look for properties (passed in by getdown) otherwise default to release
1598   private static void setGetdownAppbase()
1599   {
1600     if (getdownAppbase != null)
1601     {
1602       return;
1603     }
1604     String appbase = System.getProperty("getdownappbase");
1605     String distDir = System.getProperty("getdowndistdir");
1606     if (appbase == null)
1607     {
1608       appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1609       distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1610     }
1611     if (appbase == null)
1612     {
1613       appbase = releaseAppbase;
1614       distDir = "release";
1615     }
1616     if (appbase.endsWith("/"))
1617     {
1618       appbase = appbase.substring(0, appbase.length() - 1);
1619     }
1620     if (distDir == null)
1621     {
1622       distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1623     }
1624     getdownAppbase = appbase;
1625     getdownDistDir = distDir;
1626   }
1627
1628   public static String getGetdownAppbase()
1629   {
1630     setGetdownAppbase();
1631     return getdownAppbase;
1632   }
1633
1634   public static String getAppbaseBuildProperties()
1635   {
1636     String appbase = getGetdownAppbase();
1637     return appbase + "/" + getdownDistDir + "/build_properties";
1638   }
1639
1640   private static final Collection<String> bootstrapProperties = new ArrayList<>(
1641           Arrays.asList(JALVIEWLOGLEVEL, BOOTSTRAP_TEST));
1642
1643   public static Properties bootstrapProperties(String filename)
1644   {
1645     Properties bootstrapProps = new Properties();
1646     File file = null;
1647     if (filename != null)
1648     {
1649       file = new File(filename);
1650     }
1651     if (file == null || !file.exists())
1652     {
1653       String channelPrefsFilename = ChannelProperties
1654               .getProperty("preferences.filename");
1655       String propertiesFilename = System.getProperty("user.home")
1656               + File.separatorChar + channelPrefsFilename;
1657       file = new File(propertiesFilename);
1658     }
1659     if (file == null || !file.exists())
1660     {
1661       String releasePrefsFilename = fallbackPropertiesFile;
1662       String releasePropertiesFilename = System.getProperty("user.home")
1663               + File.separatorChar + releasePrefsFilename;
1664       file = new File(releasePropertiesFilename);
1665     }
1666
1667     if (filename == null)
1668       return null;
1669     if (!file.exists())
1670     {
1671       System.err.println("Could not load bootstrap preferences file '"
1672               + filename + "'");
1673       return null;
1674     }
1675
1676     try
1677     {
1678       FileInputStream in = new FileInputStream(file.getAbsoluteFile());
1679       Properties props = new Properties();
1680       props.load(in);
1681       for (String prop : bootstrapProperties)
1682       {
1683         if (props.containsKey(prop))
1684           bootstrapProps.put(prop, props.getProperty(prop));
1685       }
1686     } catch (FileNotFoundException e)
1687     {
1688       System.err.println("Could not find bootstrap preferences file '"
1689               + file.getAbsolutePath() + "'");
1690     } catch (IOException e)
1691     {
1692       System.err.println(
1693               "IOException when loading bootstrap preferences file '"
1694                       + file.getAbsolutePath() + "'");
1695     }
1696     return bootstrapProps;
1697   }
1698 }