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