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