JAL-629 start of tests
[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             System.out.println("# INFO: Setting default net timeout to "
537                     + orgtimeout + " 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       System.out.println(ChannelProperties.getProperty("app_name")
680               + " Version: " + codeVersion + codeInstallation);
681     }
682   }
683
684   private static void deleteBuildProperties()
685   {
686     applicationProperties.remove("LATEST_VERSION");
687     applicationProperties.remove("VERSION");
688     applicationProperties.remove("AUTHORS");
689     applicationProperties.remove("AUTHORFNAMES");
690     applicationProperties.remove("YEAR");
691     applicationProperties.remove("BUILD_DATE");
692     applicationProperties.remove("INSTALLATION");
693   }
694
695   /**
696    * Gets Jalview application property of given key. Returns null if key not
697    * found
698    * 
699    * @param key
700    *          Name of property
701    * 
702    * @return Property value
703    */
704   public static String getProperty(String key)
705   {
706     String prop = applicationProperties.getProperty(key);
707     if (prop == null && Platform.isJS())
708     {
709       prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
710               + "_" + JS_PROPERTY_PREFIX + key);
711     }
712     return prop;
713   }
714
715   /**
716    * These methods are used when checking if the saved preference is different
717    * to the default setting
718    */
719
720   public static boolean getDefault(String property, boolean def)
721   {
722     String string = getProperty(property);
723     if (string != null)
724     {
725       def = Boolean.valueOf(string).booleanValue();
726     }
727
728     return def;
729   }
730
731   public static int getDefault(String property, int def)
732   {
733     String string = getProperty(property);
734     if (string != null)
735     {
736       try
737       {
738         def = Integer.parseInt(string);
739       } catch (NumberFormatException e)
740       {
741         System.out.println("Error parsing int property '" + property
742                 + "' with value '" + string + "'");
743       }
744     }
745
746     return def;
747   }
748
749   /**
750    * Answers the value of the given property, or the supplied default value if
751    * the property is not set
752    */
753   public static String getDefault(String property, String def)
754   {
755     String value = getProperty(property);
756     return value == null ? def : value;
757   }
758
759   /**
760    * Stores property in the file "HOME_DIR/.jalview_properties"
761    * 
762    * @param key
763    *          Name of object
764    * @param obj
765    *          String value of property
766    * 
767    * @return previous value of property (or null)
768    */
769   public static Object setProperty(String key, String obj)
770   {
771     Object oldValue = null;
772     try
773     {
774       oldValue = applicationProperties.setProperty(key, obj);
775       if (propertiesFile != null && !propsAreReadOnly)
776       {
777         FileOutputStream out = new FileOutputStream(propertiesFile);
778         applicationProperties.store(out, "---JalviewX Properties File---");
779         out.close();
780       }
781     } catch (Exception ex)
782     {
783       System.out.println(
784               "Error setting property: " + key + " " + obj + "\n" + ex);
785     }
786     return oldValue;
787   }
788
789   /**
790    * remove the specified property from the jalview properties file
791    * 
792    * @param string
793    */
794   public static void removeProperty(String string)
795   {
796     applicationProperties.remove(string);
797     saveProperties();
798   }
799
800   /**
801    * save the properties to the jalview properties path
802    */
803   public static void saveProperties()
804   {
805     if (!propsAreReadOnly)
806     {
807       try
808       {
809         FileOutputStream out = new FileOutputStream(propertiesFile);
810         applicationProperties.store(out, "---JalviewX Properties File---");
811         out.close();
812       } catch (Exception ex)
813       {
814         System.out.println("Error saving properties: " + ex);
815       }
816     }
817   }
818
819   /**
820    * internal vamsas class discovery state
821    */
822   private static int vamsasJarsArePresent = -1;
823
824   /**
825    * Searches for vamsas client classes on class path.
826    * 
827    * @return true if vamsas client is present on classpath
828    */
829   public static boolean vamsasJarsPresent()
830   {
831     if (vamsasJarsArePresent == -1)
832     {
833       try
834       {
835         if (jalview.jbgui.GDesktop.class.getClassLoader()
836                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
837         {
838           Console.debug(
839                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
840           vamsasJarsArePresent = 1;
841           JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
842                   Console.getCachedLogLevel("logs.Vamsas.Level"));
843           JLoggerLog4j.addAppender(lvclient, Console.log,
844                   JALVIEW_LOGGER_NAME);
845           // Tell the user that debug is enabled
846           lvclient.debug(ChannelProperties.getProperty("app_name")
847                   + " Vamsas Client Debugging Output Follows.");
848         }
849       } catch (Exception e)
850       {
851         vamsasJarsArePresent = 0;
852         Console.debug("Vamsas Classes are not present");
853       }
854     }
855     return (vamsasJarsArePresent > 0);
856   }
857
858   /**
859    * internal vamsas class discovery state
860    */
861   private static int groovyJarsArePresent = -1;
862
863   /**
864    * Searches for vamsas client classes on class path.
865    * 
866    * @return true if vamsas client is present on classpath
867    */
868   public static boolean groovyJarsPresent()
869   {
870     if (groovyJarsArePresent == -1)
871     {
872       try
873       {
874         if (Cache.class.getClassLoader()
875                 .loadClass("groovy.lang.GroovyObject") != null)
876         {
877           Console.debug(
878                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
879           groovyJarsArePresent = 1;
880           JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
881                   Console.getCachedLogLevel("logs.Groovy.Level"));
882           JLoggerLog4j.addAppender(lgclient, Console.log,
883                   JALVIEW_LOGGER_NAME);
884           // Tell the user that debug is enabled
885           lgclient.debug(ChannelProperties.getProperty("app_name")
886                   + " Groovy Client Debugging Output Follows.");
887         }
888       } catch (Error e)
889       {
890         groovyJarsArePresent = 0;
891         Console.debug("Groovy Classes are not present", e);
892       } catch (Exception e)
893       {
894         groovyJarsArePresent = 0;
895         Console.debug("Groovy Classes are not present");
896       }
897     }
898     return (groovyJarsArePresent > 0);
899   }
900
901   /**
902    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
903    * enabled.
904    */
905   protected static Object tracker = null;
906
907   protected static Class trackerfocus = null;
908
909   protected static Class jgoogleanalyticstracker = null;
910
911   /**
912    * Initialise the google tracker if it is not done already.
913    */
914   public static void initGoogleTracker()
915   {
916     if (tracker == null)
917     {
918       if (jgoogleanalyticstracker == null)
919       {
920         // try to get the tracker class
921         try
922         {
923           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
924                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
925           trackerfocus = Cache.class.getClassLoader()
926                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
927         } catch (Exception e)
928         {
929           Console.debug(
930                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
931           tracker = null;
932           jgoogleanalyticstracker = null;
933           trackerfocus = null;
934           return;
935         }
936       }
937       // now initialise tracker
938       Exception re = null, ex = null;
939       Error err = null;
940       String vrs = "No Version Accessible";
941       try
942       {
943         // Google analytics tracking code for Library Finder
944         tracker = jgoogleanalyticstracker
945                 .getConstructor(new Class[]
946                 { String.class, String.class, String.class })
947                 .newInstance(new Object[]
948                 { ChannelProperties.getProperty("app_name") + " Desktop",
949                     (vrs = Cache.getProperty("VERSION") + "_"
950                             + Cache.getDefault("BUILD_DATE", "unknown")),
951                     "UA-9060947-1" });
952         jgoogleanalyticstracker
953                 .getMethod("trackAsynchronously", new Class[]
954                 { trackerfocus })
955                 .invoke(tracker, new Object[]
956                 { trackerfocus.getConstructor(new Class[] { String.class })
957                         .newInstance(new Object[]
958                         { "Application Started." }) });
959       } catch (RuntimeException e)
960       {
961         re = e;
962       } catch (Exception e)
963       {
964         ex = e;
965       } catch (Error e)
966       {
967         err = e;
968       }
969       if (re != null || ex != null || err != null)
970       {
971         if (re != null)
972         {
973           Console.debug("Caught runtime exception in googletracker init:",
974                   re);
975         }
976         if (ex != null)
977         {
978           Console.warn(
979                   "Failed to initialise GoogleTracker for Jalview Desktop with version "
980                           + vrs,
981                   ex);
982         }
983         if (err != null)
984         {
985           Console.error(
986                   "Whilst initing GoogleTracker for Jalview Desktop version "
987                           + vrs,
988                   err);
989         }
990       }
991       else
992       {
993         Console.debug("Successfully initialised tracker.");
994       }
995     }
996   }
997
998   /**
999    * get the user's default colour if available
1000    * 
1001    * @param property
1002    * @param defcolour
1003    * @return
1004    */
1005   public static Color getDefaultColour(String property, Color defcolour)
1006   {
1007     String colprop = getProperty(property);
1008     if (colprop == null)
1009     {
1010       return defcolour;
1011     }
1012     Color col = ColorUtils.parseColourString(colprop);
1013     if (col == null)
1014     {
1015       Console.warn("Couldn't parse '" + colprop + "' as a colour for "
1016               + property);
1017     }
1018     return (col == null) ? defcolour : col;
1019   }
1020
1021   /**
1022    * store a colour as a Jalview user default property
1023    * 
1024    * @param property
1025    * @param colour
1026    */
1027   public static void setColourProperty(String property, Color colour)
1028   {
1029     setProperty(property, jalview.util.Format.getHexString(colour));
1030   }
1031
1032   /**
1033    * Stores a formatted date in a jalview property, using a fixed locale.
1034    * 
1035    * @param propertyName
1036    * @param date
1037    * @return the formatted date string
1038    */
1039   public static String setDateProperty(String propertyName, Date date)
1040   {
1041     String formatted = date_format.format(date);
1042     setProperty(propertyName, formatted);
1043     return formatted;
1044   }
1045
1046   /**
1047    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1048    * format) and returns as a Date, or null if parsing fails
1049    * 
1050    * @param propertyName
1051    * @return
1052    * 
1053    */
1054   public static Date getDateProperty(String propertyName)
1055   {
1056     String val = getProperty(propertyName);
1057     if (val != null)
1058     {
1059       try
1060       {
1061         return date_format.parse(val);
1062       } catch (Exception ex)
1063       {
1064         System.err.println("Invalid or corrupt date in property '"
1065                 + propertyName + "' : value was '" + val + "'");
1066       }
1067     }
1068     return null;
1069   }
1070
1071   /**
1072    * get and parse a property as an integer. send any parsing problems to
1073    * System.err
1074    * 
1075    * @param property
1076    * @return null or Integer
1077    */
1078   public static Integer getIntegerProperty(String property)
1079   {
1080     String val = getProperty(property);
1081     if (val != null && (val = val.trim()).length() > 0)
1082     {
1083       try
1084       {
1085         return Integer.valueOf(val);
1086       } catch (NumberFormatException x)
1087       {
1088         System.err.println("Invalid integer in property '" + property
1089                 + "' (value was '" + val + "')");
1090       }
1091     }
1092     return null;
1093   }
1094
1095   /**
1096    * Set the specified value, or remove it if null or empty. Does not save the
1097    * properties file.
1098    * 
1099    * @param propName
1100    * @param value
1101    */
1102   public static void setOrRemove(String propName, String value)
1103   {
1104     if (propName == null)
1105     {
1106       return;
1107     }
1108     if (value == null || value.trim().length() < 1)
1109     {
1110       Cache.applicationProperties.remove(propName);
1111     }
1112     else
1113     {
1114       Cache.applicationProperties.setProperty(propName, value);
1115     }
1116   }
1117
1118   /**
1119    * Loads in user colour schemes from files.
1120    * 
1121    * @param files
1122    *          a '|'-delimited list of file paths
1123    */
1124   public static void initUserColourSchemes(String files)
1125   {
1126     if (files == null || files.length() == 0)
1127     {
1128       return;
1129     }
1130
1131     // In case colours can't be loaded, we'll remove them
1132     // from the default list here.
1133     StringBuffer coloursFound = new StringBuffer();
1134     StringTokenizer st = new StringTokenizer(files, "|");
1135     while (st.hasMoreElements())
1136     {
1137       String file = st.nextToken();
1138       try
1139       {
1140         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1141         if (ucs != null)
1142         {
1143           if (coloursFound.length() > 0)
1144           {
1145             coloursFound.append("|");
1146           }
1147           coloursFound.append(file);
1148           ColourSchemes.getInstance().registerColourScheme(ucs);
1149         }
1150       } catch (Exception ex)
1151       {
1152         System.out.println("Error loading User ColourFile\n" + ex);
1153       }
1154     }
1155     if (!files.equals(coloursFound.toString()))
1156     {
1157       if (coloursFound.toString().length() > 1)
1158       {
1159         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1160                 coloursFound.toString());
1161       }
1162       else
1163       {
1164         applicationProperties
1165                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1166       }
1167     }
1168   }
1169
1170   /**
1171    * Initial logging information helper for various versions output
1172    * 
1173    * @param prefix
1174    * @param value
1175    * @param defaultValue
1176    */
1177   private static void appendIfNotNull(StringBuilder sb, String prefix,
1178           String value, String suffix, String defaultValue)
1179   {
1180     if (value == null && defaultValue == null)
1181     {
1182       return;
1183     }
1184     if (prefix != null)
1185       sb.append(prefix);
1186     sb.append(value == null ? defaultValue : value);
1187     if (suffix != null)
1188       sb.append(suffix);
1189   }
1190
1191   /**
1192    * 
1193    * @return Jalview version, build details and JVM platform version for console
1194    */
1195   public static String getVersionDetailsForConsole()
1196   {
1197     StringBuilder sb = new StringBuilder();
1198     sb.append(ChannelProperties.getProperty("app_name"))
1199             .append(" Version: ");
1200     sb.append(Cache.getDefault("VERSION", "TEST"));
1201     sb.append("\n");
1202     sb.append(ChannelProperties.getProperty("app_name"))
1203             .append(" Installation: ");
1204     sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1205     sb.append("\n");
1206     sb.append("Build Date: ");
1207     sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1208     sb.append("\n");
1209     sb.append("Java version: ");
1210     sb.append(System.getProperty("java.version"));
1211     sb.append("\n");
1212     sb.append("Java platform: ");
1213     sb.append(System.getProperty("os.arch"));
1214     sb.append(" ");
1215     sb.append(System.getProperty("os.name"));
1216     sb.append(" ");
1217     sb.append(System.getProperty("os.version"));
1218     sb.append("\n");
1219     appendIfNotNull(sb, "Install4j version: ",
1220             System.getProperty("sys.install4jVersion"), "\n", null);
1221     appendIfNotNull(sb, "Install4j template version: ",
1222             System.getProperty("installer_template_version"), "\n", null);
1223     appendIfNotNull(sb, "Launcher version: ",
1224             System.getProperty("launcher_version"), "\n", null);
1225     LookAndFeel laf = UIManager.getLookAndFeel();
1226     String lafName = laf == null ? "Not obtained" : laf.getName();
1227     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1228     sb.append("LookAndFeel: ");
1229     sb.append(lafName);
1230     sb.append(" (");
1231     sb.append(lafClass);
1232     sb.append(")\n");
1233     appendIfNotNull(sb, "Channel: ",
1234             ChannelProperties.getProperty("channel"), "\n", null);
1235     if (Console.isDebugEnabled()
1236             || !"release".equals(ChannelProperties.getProperty("channel")))
1237     {
1238       appendIfNotNull(sb, "Getdown appdir: ",
1239               System.getProperty("getdowninstanceappdir"), "\n", null);
1240       appendIfNotNull(sb, "Getdown appbase: ",
1241               System.getProperty("getdowninstanceappbase"), "\n", null);
1242       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1243               "\n", "unknown");
1244       appendIfNotNull(sb, "Preferences file: ", propertiesFile, "\n",
1245               "unknown");
1246     }
1247     return sb.toString();
1248   }
1249
1250   /**
1251    * 
1252    * @return build details as reported in splashscreen
1253    */
1254   public static String getBuildDetailsForSplash()
1255   {
1256     // consider returning more human friendly info
1257     // eg 'built from Source' or update channel
1258     return Cache.getDefault("INSTALLATION", "unknown");
1259   }
1260
1261   public static String getStackTraceString(Throwable t)
1262   {
1263     StringWriter sw = new StringWriter();
1264     PrintWriter pw = new PrintWriter(sw);
1265     t.printStackTrace(pw);
1266     return sw.toString();
1267   }
1268
1269   // proxy properties methods
1270   public static void clearProxyProperties()
1271   {
1272     setProxyProperties(null, null, null, null, null, null, null, null,
1273             null);
1274   }
1275
1276   public static void resetProxyProperties()
1277   {
1278     setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1279             startupProxyProperties[2], startupProxyProperties[3],
1280             startupProxyProperties[4],
1281             startupProxyProperties[5] == null ? null
1282                     : startupProxyProperties[5].toCharArray(),
1283             startupProxyProperties[6],
1284             startupProxyProperties[7] == null ? null
1285                     : startupProxyProperties[7].toCharArray(),
1286             startupProxyProperties[8]);
1287     StringBuilder sb = new StringBuilder();
1288     sb.append("Setting proxy properties to: http.proxyHost=")
1289             .append(startupProxyProperties[0]).append(", http.proxyPort=")
1290             .append(startupProxyProperties[1])
1291             .append(startupProxyProperties[4] != null
1292                     && !startupProxyProperties[4].isEmpty()
1293                             ? " [" + startupProxyProperties[4] + "]"
1294                             : "")
1295             .append(", https.proxyHost=").append(startupProxyProperties[2])
1296             .append(", https.proxyPort=").append(startupProxyProperties[3])
1297             .append(startupProxyProperties[6] != null
1298                     && !startupProxyProperties[6].isEmpty()
1299                             ? " [" + startupProxyProperties[6] + "]"
1300                             : "");
1301
1302     Console.debug(sb.toString());
1303   }
1304
1305   public static void setProxyPropertiesFromPreferences()
1306   {
1307     setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1308   }
1309
1310   public static void setProxyPropertiesFromPreferences(
1311           String previousProxyType)
1312   {
1313     String proxyType = Cache.getDefault("USE_PROXY",
1314             Cache.PROXYTYPE_SYSTEM);
1315     if (previousProxyType != null
1316             && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1317                                                          // customProxy
1318             && proxyType.equals(previousProxyType))
1319     {
1320       // no change
1321       return;
1322     }
1323     switch (proxyType)
1324     {
1325     case Cache.PROXYTYPE_NONE:
1326       if (!previousProxyType.equals(proxyType))
1327       {
1328         Console.info("Setting no proxy settings");
1329         Cache.setProxyProperties(null, null, null, null, null, null, null,
1330                 null, null);
1331       }
1332       break;
1333     case Cache.PROXYTYPE_CUSTOM:
1334       // always re-set a custom proxy -- it might have changed, particularly
1335       // password
1336       Console.info("Setting custom proxy settings");
1337       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1338       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1339               Cache.getDefault("PROXY_PORT", null),
1340               Cache.getDefault("PROXY_SERVER_HTTPS", null),
1341               Cache.getDefault("PROXY_PORT_HTTPS", null),
1342               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1343                       : null,
1344               proxyAuthSet ? Cache.proxyAuthPassword : null,
1345               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1346                       : null,
1347               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1348       break;
1349     default: // system proxy settings by default
1350       Console.info("Setting system proxy settings");
1351       Cache.resetProxyProperties();
1352     }
1353   }
1354
1355   public static void setProxyProperties(String httpHost, String httpPort,
1356           String httpsHost, String httpsPort, String httpUser,
1357           char[] httpPassword, String httpsUser, char[] httpsPassword,
1358           String nonProxyHosts)
1359   {
1360     setOrClearSystemProperty("http.proxyHost", httpHost);
1361     setOrClearSystemProperty("http.proxyPort", httpPort);
1362     setOrClearSystemProperty("https.proxyHost", httpsHost);
1363     setOrClearSystemProperty("https.proxyPort", httpsPort);
1364     setOrClearSystemProperty("http.proxyUser", httpUser);
1365     setOrClearSystemProperty("https.proxyUser", httpsUser);
1366     // note: passwords for http.proxyPassword and https.proxyPassword are sent
1367     // via the Authenticator, properties do not need to be set
1368
1369     // are we using a custom proxy (password prompt might be required)?
1370     boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1371             .equals(PROXYTYPE_CUSTOM);
1372
1373     /*
1374      * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1375      * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1376      * is not re-called).
1377      * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1378      * the AuthCache.
1379      * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1380      * ...
1381      * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1382      */
1383     /*
1384     try
1385     {
1386       sun.net.www.protocol.http.AuthCacheValue
1387               .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1388     } catch (Throwable t)
1389     {
1390       Cache.error(t.getMessage());
1391       Cache.debug(getStackTraceString(t));
1392     }
1393     */
1394
1395     if (httpUser != null || httpsUser != null)
1396     {
1397       try
1398       {
1399         char[] displayHttpPw = new char[httpPassword == null ? 0
1400                 : httpPassword.length];
1401         Arrays.fill(displayHttpPw, '*');
1402         Console.debug(
1403                 "CACHE Proxy: setting new Authenticator with httpUser='"
1404                         + httpUser + "' httpPassword='" + displayHttpPw
1405                         + "'");
1406         if (!Platform.isJS())
1407         /* *
1408          * java.net.Authenticator not implemented in SwingJS yet
1409          * 
1410          * @j2sIgnore
1411          * 
1412          */
1413         {
1414           Authenticator.setDefault(new Authenticator()
1415           {
1416             @Override
1417             protected PasswordAuthentication getPasswordAuthentication()
1418             {
1419               if (getRequestorType() == RequestorType.PROXY)
1420               {
1421                 String protocol = getRequestingProtocol();
1422                 boolean needProxyPasswordSet = false;
1423                 if (customProxySet &&
1424                 // we have a username but no password for the scheme being
1425                 // requested
1426                         (protocol.equalsIgnoreCase("http")
1427                                 && (httpUser != null
1428                                         && httpUser.length() > 0
1429                                         && (httpPassword == null
1430                                                 || httpPassword.length == 0)))
1431                         || (protocol.equalsIgnoreCase("https")
1432                                 && (httpsUser != null
1433                                         && httpsUser.length() > 0
1434                                         && (httpsPassword == null
1435                                                 || httpsPassword.length == 0))))
1436                 {
1437                   // open Preferences -> Connections
1438                   String message = MessageManager
1439                           .getString("label.proxy_password_required");
1440                   Preferences.openPreferences(
1441                           Preferences.TabRef.CONNECTIONS_TAB, message);
1442                   Preferences.getInstance()
1443                           .proxyAuthPasswordCheckHighlight(true, true);
1444                 }
1445                 else
1446                 {
1447                   try
1448                   {
1449                     if (protocol.equalsIgnoreCase("http")
1450                             && getRequestingHost()
1451                                     .equalsIgnoreCase(httpHost)
1452                             && getRequestingPort() == Integer
1453                                     .valueOf(httpPort))
1454                     {
1455                       Console.debug(
1456                               "AUTHENTICATOR returning PasswordAuthentication(\""
1457                                       + httpUser + "\", '"
1458                                       + new String(displayHttpPw) + "')");
1459                       return new PasswordAuthentication(httpUser,
1460                               httpPassword);
1461                     }
1462                     if (protocol.equalsIgnoreCase("https")
1463                             && getRequestingHost()
1464                                     .equalsIgnoreCase(httpsHost)
1465                             && getRequestingPort() == Integer
1466                                     .valueOf(httpsPort))
1467                     {
1468                       char[] displayHttpsPw = new char[httpPassword.length];
1469                       Arrays.fill(displayHttpsPw, '*');
1470                       Console.debug(
1471                               "AUTHENTICATOR returning PasswordAuthentication(\""
1472                                       + httpsUser + "\", '" + displayHttpsPw
1473                                       + "'");
1474                       return new PasswordAuthentication(httpsUser,
1475                               httpsPassword);
1476                     }
1477                   } catch (NumberFormatException e)
1478                   {
1479                     Console.error("Problem with proxy port values [http:"
1480                             + httpPort + ", https:" + httpsPort + "]");
1481                   }
1482                   Console.debug(
1483                           "AUTHENTICATOR after trying to get PasswordAuthentication");
1484                 }
1485               }
1486               // non proxy request
1487               Console.debug("AUTHENTICATOR returning null");
1488               return null;
1489             }
1490           });
1491         } // end of j2sIgnore for java.net.Authenticator
1492
1493         // required to re-enable basic authentication (should be okay for a
1494         // local proxy)
1495         Console.debug(
1496                 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1497         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1498       } catch (SecurityException e)
1499       {
1500         Console.error("Could not set default Authenticator");
1501         Console.debug(getStackTraceString(e));
1502       }
1503     }
1504     else
1505     {
1506       // reset the Authenticator to protect http.proxyUser and
1507       // http.proxyPassword Just In Case
1508       /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1509        * has working credentials. No workaround for Java 11.
1510        */
1511       if (!Platform.isJS())
1512       /* *
1513        * java.net.Authenticator not implemented in SwingJS yet
1514        * 
1515        * @j2sIgnore
1516        * 
1517        */
1518       {
1519         Console.debug(
1520                 "AUTHENTICATOR setting default Authenticator to null");
1521         Authenticator.setDefault(null);
1522       }
1523     }
1524
1525     // nonProxyHosts not currently configurable in Preferences
1526     Console.debug(
1527             "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1528                     + nonProxyHosts + "\"");
1529     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1530   }
1531
1532   public static void setOrClearSystemProperty(String key, char[] value)
1533   {
1534     setOrClearSystemProperty(key,
1535             (value == null) ? null : new String(value));
1536   }
1537
1538   public static void setOrClearSystemProperty(String key, String value)
1539   {
1540     if (key == null)
1541     {
1542       return;
1543     }
1544     if (value == null)
1545     {
1546       System.clearProperty(key);
1547     }
1548     else
1549     {
1550       System.setProperty(key, value);
1551     }
1552   }
1553
1554   /**
1555    * Getdown appbase methods
1556    */
1557
1558   private static final String releaseAppbase;
1559
1560   private static String getdownAppbase;
1561
1562   private static String getdownDistDir;
1563
1564   static
1565   {
1566     if (!Platform.isJS())
1567     {
1568       Float specversion = Float
1569               .parseFloat(System.getProperty("java.specification.version"));
1570       releaseAppbase = (specversion < 9)
1571               ? "https://www.jalview.org/getdown/release/1.8"
1572               : "https://www.jalview.org/getdown/release/11";
1573     }
1574     else
1575     {
1576       // this value currenly made up, can be changed to URL that will be
1577       // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1578       releaseAppbase = "https://www.jalview.org/jalview-js";
1579       getdownAppbase = releaseAppbase;
1580       getdownDistDir = "/swingjs/j2s";
1581     }
1582   }
1583
1584   // look for properties (passed in by getdown) otherwise default to release
1585   private static void setGetdownAppbase()
1586   {
1587     if (getdownAppbase != null)
1588     {
1589       return;
1590     }
1591     String appbase = System.getProperty("getdownappbase");
1592     String distDir = System.getProperty("getdowndistdir");
1593     if (appbase == null)
1594     {
1595       appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1596       distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1597     }
1598     if (appbase == null)
1599     {
1600       appbase = releaseAppbase;
1601       distDir = "release";
1602     }
1603     if (appbase.endsWith("/"))
1604     {
1605       appbase = appbase.substring(0, appbase.length() - 1);
1606     }
1607     if (distDir == null)
1608     {
1609       distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1610     }
1611     getdownAppbase = appbase;
1612     getdownDistDir = distDir;
1613   }
1614
1615   public static String getGetdownAppbase()
1616   {
1617     setGetdownAppbase();
1618     return getdownAppbase;
1619   }
1620
1621   public static String getAppbaseBuildProperties()
1622   {
1623     String appbase = getGetdownAppbase();
1624     return appbase + "/" + getdownDistDir + "/build_properties";
1625   }
1626
1627   private static final Collection<String> bootstrapProperties = new ArrayList<>(
1628           Arrays.asList(JALVIEWLOGLEVEL, BOOTSTRAP_TEST));
1629
1630   public static Properties bootstrapProperties(String filename)
1631   {
1632     Properties bootstrapProps = new Properties();
1633     File file = null;
1634     if (filename != null)
1635     {
1636       file = new File(filename);
1637     }
1638     if (file == null || !file.exists())
1639     {
1640       String channelPrefsFilename = ChannelProperties
1641               .getProperty("preferences.filename");
1642       String propertiesFilename = System.getProperty("user.home")
1643               + File.separatorChar + channelPrefsFilename;
1644       file = new File(propertiesFilename);
1645     }
1646     if (file == null || !file.exists())
1647     {
1648       String releasePrefsFilename = fallbackPropertiesFile;
1649       String releasePropertiesFilename = System.getProperty("user.home")
1650               + File.separatorChar + releasePrefsFilename;
1651       file = new File(releasePropertiesFilename);
1652     }
1653
1654     if (filename == null || !file.exists())
1655     {
1656       System.err.println("Could not load bootstrap preferences file '"
1657               + filename + "'");
1658       return null;
1659     }
1660
1661     try
1662     {
1663       FileInputStream in = new FileInputStream(file.getAbsoluteFile());
1664       Properties props = new Properties();
1665       props.load(in);
1666       for (String prop : bootstrapProperties)
1667       {
1668         if (props.containsKey(prop))
1669           bootstrapProps.put(prop, props.getProperty(prop));
1670       }
1671     } catch (FileNotFoundException e)
1672     {
1673       System.err.println("Could not find bootstrap preferences file '"
1674               + file.getAbsolutePath() + "'");
1675     } catch (IOException e)
1676     {
1677       System.err.println(
1678               "IOException when loading bootstrap preferences file '"
1679                       + file.getAbsolutePath() + "'");
1680     }
1681     return bootstrapProps;
1682   }
1683 }