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