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