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