JAL-3933 remove obsolete Castor logging configuration
[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.text.DateFormat;
33 import java.text.SimpleDateFormat;
34 import java.util.Collections;
35 import java.util.Date;
36 import java.util.Enumeration;
37 import java.util.Locale;
38 import java.util.Properties;
39 import java.util.StringTokenizer;
40 import java.util.TreeSet;
41 import java.util.regex.Pattern;
42
43 import javax.swing.LookAndFeel;
44 import javax.swing.UIManager;
45
46 import org.apache.log4j.ConsoleAppender;
47 import org.apache.log4j.Level;
48 import org.apache.log4j.Logger;
49 import org.apache.log4j.SimpleLayout;
50 import org.apache.log4j.builders.appender.ConsoleAppenderBuilder;
51 import org.apache.logging.log4j.core.config.Configurator;
52 import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
53 import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
54 import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
55 import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
56
57 import jalview.datamodel.PDBEntry;
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.ColorUtils;
65 import jalview.ws.sifts.SiftsSettings;
66
67 /**
68  * Stores and retrieves Jalview Application Properties Lists and fields within
69  * list entries are separated by '|' symbols unless otherwise stated (|) clauses
70  * are alternative values for a tag. <br>
71  * <br>
72  * Current properties include:
73  * <ul>
74  * <br>
75  * logs.Axis.Level - one of the stringified Levels for log4j controlling the
76  * logging level for axis (used for web services) <br>
77  * </li>
78  * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
79  * the logging level for castor (used for serialization) <br>
80  * </li>
81  * <li>logs.Jalview.Level - Cache.log stringified level. <br>
82  * </li>
83  * <li>SCREEN_WIDTH</li>
84  * <li>SCREEN_HEIGHT</li>
85  * <li>SCREEN_Y=285</li>
86  * <li>SCREEN_X=371</li>
87  * <li>SHOW_FULLSCREEN boolean</li>
88  * <li>FONT_NAME java font name for alignment text display</li>
89  * <li>FONT_SIZE size of displayed alignment text</li>
90  * <li>FONT_STYLE style of font displayed (sequence labels are always
91  * italic)</li>
92  * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
93  * <li>LAST_DIRECTORY last directory for browsing alignment</li>
94  * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
95  * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
96  * <li>SHOW_IDENTITY show percentage identity annotation</li>
97  * <li>SHOW_QUALITY show alignment quality annotation</li>
98  * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
99  * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
100  * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
101  * LABEL_AND_SEQUENCE</li>
102  * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
103  * sequence annotations</li>
104  * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
105  * annotation row</li>
106  * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
107  * <li>DEFAULT_FILE_FORMAT file format used to save</li>
108  * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
109  * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
110  * <li>VERSION the version of the jalview build</li>
111  * <li>BUILD_DATE date of this build</li>
112  * <li>LATEST_VERSION the latest jalview version advertised on the
113  * www.jalview.org</li>
114  * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
115  * descriptions</li>
116  * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
117  * suffix to file</li>
118  * <li>RECENT_URL list of recently retrieved URLs</li>
119  * <li>RECENT_FILE list of recently opened files</li>
120  * <li>USE_PROXY flag for whether a http proxy is to be used</li>
121  * <li>PROXY_SERVER the proxy</li>
122  * <li>PROXY_PORT</li>
123  * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
124  * service</li>
125  * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
126  * service</li>
127  * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
128  * collecting usage statistics</li>
129  * <li>SHOW_OVERVIEW boolean for overview window display</li>
130  * <li>ANTI_ALIAS boolean for smooth fonts</li>
131  * <li>RIGHT_ALIGN_IDS boolean</li>
132  * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
133  * <li>PAD_GAPS boolean</li>
134  * <li>ID_ITALICS boolean</li>
135  * <li>SHOW_JV_SUFFIX</li>
136  * <li>WRAP_ALIGNMENT</li>
137  * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
138  * style check</li>
139  * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
140  * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
141  * $SEQUENCE_ID$</li>
142  * <li>STORED_LINKS list of name|url pairs which user has entered but are not
143  * currently used
144  * <li>DEFAULT_LINK name of single url to be used when user double clicks a
145  * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
146  * <li>GROUP_LINKS list of name|URL[|&lt;separator&gt;] tuples - see
147  * jalview.utils.GroupURLLink for more info</li>
148  * <li>DEFAULT_BROWSER for unix</li>
149  * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
150  * (false)</li>
151  * <li>VERSION_CHECK (true) check for the latest release version from
152  * www.jalview.org (or the alias given by the www.jalview.org property)</li>
153  * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
154  * ID tooltip</li>
155  * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
156  * ID tooltip</li>
157  * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
158  * displayed as '.'</li>
159  * <li>SORT_BY_TREE (false) sort the current alignment view according to the
160  * order of a newly displayed tree</li>
161  * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
162  * sequence ID strings before attempting retrieval from any datasource</li>
163  * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
164  * alignment.</li>
165  * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
166  * in the alignment.</li>
167  * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
168  * histogram.</li>
169  * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
170  * logo.</li>
171  * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
172  * logo normalised to row height rather than histogram height.</li>
173  * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
174  * respond to selections made in other alignments containing the same sequences.
175  * </li>
176  * <li>SHOW_JWS2_SERVICES (true) when set to false, jalview will not
177  * auto-discover JABAWS services</li>
178  * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
179  * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
180  * warning dialog box is displayed.</li>
181  * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
182  * when shading by annotation</li>
183  * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
184  * when shading by annotation</li>
185  * <li>www.jalview.org (https://www.jalview.org) a property enabling all HTTP
186  * requests to be redirected to a mirror of https://www.jalview.org</li>
187  * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
188  * alignment figure to accommodate even the longest sequence ID or annotation
189  * label.</li>
190  * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
191  * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
192  * will override this).</li>
193  * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
194  * record</li>
195  * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
196  * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
197  * display</li>
198  * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
199  * display</li>
200  * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
201  * display</li>
202  * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
203  * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
204  * </li>
205  * <li>NONEWS - when set disables Jalview News from automatically appearing</li>
206  * <li>NOHTMLTEMPLATES - when set, the
207  * https://github.com/jalview/exporter-templates/tree/master/biojs repository is
208  * not downloaded automatically</li>
209  * <li>NOIDENTIFIERSSERVICE - when set, jalview won't automatically download
210  * available URL linkouts via www.jalview.org/services/identifiers</li>
211  * <li>
212  * </ul>
213  * Deprecated settings:
214  * <ul>
215  * *
216  * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
217  * startup (JWS1 services only)</li>
218  * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
219  * (JWS1 services only)</li>
220  * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
221  * services in the desktop GUI</li>
222  * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
223  * panel in web service preferences</li>
224  * </ul>
225  * 
226  * @author $author$
227  * @version $Revision$
228  */
229 public class Cache
230 {
231   /**
232    * property giving log4j level for CASTOR loggers
233    */
234   public static final String CASTORLOGLEVEL = "logs.Castor.level";
235
236   /**
237    * property giving log4j level for AXIS loggers
238    */
239   public static final String AXISLOGLEVEL = "logs.Axis.level";
240
241   /**
242    * property giving log4j level for Jalview Log
243    */
244   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
245
246   /**
247    * Sifts settings
248    */
249   public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
250           .getProperty("user.home") + File.separatorChar
251           + ".sifts_downloads" + File.separatorChar;
252
253   private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
254
255   private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
256
257   /**
258    * Identifiers.org download settings
259    */
260   private static final String ID_ORG_FILE = System.getProperty("user.home")
261           + File.separatorChar + ".identifiers.org.ids.json";
262
263   /**
264    * Allowed values are PDB or mmCIF
265    */
266   private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
267           .toString();
268
269   private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
270           .toString();
271
272   /*
273    * a date formatter using a fixed (rather than the user's) locale; 
274    * this ensures that date properties can be written and re-read successfully
275    * even if the user changes their locale setting
276    */
277   private static final DateFormat date_format = SimpleDateFormat
278           .getDateTimeInstance(SimpleDateFormat.MEDIUM,
279                   SimpleDateFormat.MEDIUM, Locale.UK);
280
281   /**
282    * Initialises the Jalview Application Log
283    */
284   public static Logger log;
285
286   /** Jalview Properties */
287   public static Properties applicationProperties = new Properties()
288   {
289     // override results in properties output in alphabetical order
290     @Override
291     public synchronized Enumeration<Object> keys()
292     {
293       return Collections.enumeration(new TreeSet<>(super.keySet()));
294     }
295   };
296
297   /** Default file is ~/.jalview_properties */
298   static String propertiesFile;
299
300   private static boolean propsAreReadOnly = false;
301
302   public static void initLogger()
303   {
304     if (log != null)
305     {
306       return;
307     }
308     try
309     {
310       // TODO: redirect stdout and stderr here in order to grab the output of
311       // the log
312       ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
313       AppenderComponentBuilder consoleApp = builder.newAppender("stderr", "Console");
314       builder.add(consoleApp);
315       Configurator.initialize(builder.build());
316       // log output
317       Logger laxis = Logger.getLogger("org.apache.axis");
318       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
319
320       laxis.setLevel(Level.toLevel(
321               Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
322       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
323       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
324       // Level.INFO.toString())));
325       // we shouldn't need to do this
326       org.apache.log4j.Logger.getRootLogger()
327               .setLevel(org.apache.log4j.Level.INFO);
328
329       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
330               .getDefault("logs.Jalview.level", Level.INFO.toString())));
331       // laxis.addAppender(ap);
332       // lcastor.addAppender(ap);
333       // jalview.bin.Cache.log.addAppender(ap);
334       // Tell the user that debug is enabled
335       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
336     } catch (Exception ex)
337     {
338       System.err.println("Problems initializing the log4j system\n");
339       ex.printStackTrace(System.err);
340     }
341   }
342
343   /**
344    * Loads properties from the given properties file. Any existing properties
345    * are first cleared.
346    */
347   public static void loadProperties(String propsFile)
348   {
349     propertiesFile = propsFile;
350     if (propsFile == null)
351     {
352       propertiesFile = System.getProperty("user.home") + File.separatorChar
353               + ".jalview_properties";
354     }
355     else
356     {
357       // don't corrupt the file we've been given.
358       propsAreReadOnly = true;
359     }
360
361     try
362     {
363       InputStream fis;
364       try
365       {
366         fis = new java.net.URL(propertiesFile).openStream();
367         System.out.println(
368                 "Loading jalview properties from : " + propertiesFile);
369         System.out.println(
370                 "Disabling Jalview writing to user's local properties file.");
371         propsAreReadOnly = true;
372
373       } catch (Exception ex)
374       {
375         fis = null;
376       }
377       if (fis == null)
378       {
379         fis = new FileInputStream(propertiesFile);
380       }
381       applicationProperties.clear();
382       applicationProperties.load(fis);
383
384       // remove any old build properties
385
386       deleteBuildProperties();
387       fis.close();
388     } catch (Exception ex)
389     {
390       System.out.println("Error reading properties file: " + ex);
391     }
392
393     if (getDefault("USE_PROXY", false))
394     {
395       String proxyServer = getDefault("PROXY_SERVER", ""),
396               proxyPort = getDefault("PROXY_PORT", "8080");
397
398       System.out.println("Using proxyServer: " + proxyServer
399               + " proxyPort: " + proxyPort);
400
401       System.setProperty("http.proxyHost", proxyServer);
402       System.setProperty("http.proxyPort", proxyPort);
403     }
404
405     // LOAD THE AUTHORS FROM THE authors.props file
406     try
407     {
408       String authorDetails = "jar:"
409               .concat(Cache.class.getProtectionDomain().getCodeSource()
410                       .getLocation().toString().concat("!/authors.props"));
411
412       java.net.URL localJarFileURL = new java.net.URL(authorDetails);
413
414       InputStream in = localJarFileURL.openStream();
415       applicationProperties.load(in);
416       in.close();
417     } catch (Exception ex)
418     {
419       System.out.println("Error reading author details: " + ex);
420       applicationProperties.remove("AUTHORS");
421       applicationProperties.remove("AUTHORFNAMES");
422       applicationProperties.remove("YEAR");
423     }
424
425     loadBuildProperties(false);
426
427     SiftsSettings
428             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
429
430     SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
431             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
432
433     SiftsSettings.setFailSafePIDThreshold(
434             jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
435                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
436
437     SiftsSettings.setCacheThresholdInDays(
438             jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
439                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
440
441     IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
442             "https://www.jalview.org/services/identifiers"));
443     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
444
445     StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
446             .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
447     StructureImportSettings
448             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
449     // StructureImportSettings
450     // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
451     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
452
453     String jnlpVersion = System.getProperty("jalview.version");
454
455     // jnlpVersion will be null if a latest version check for the channel needs
456     // to be done
457     // Dont do this check if running in headless mode
458
459     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
460             && (System.getProperty("java.awt.headless") == null || System
461                     .getProperty("java.awt.headless").equals("false")))
462     {
463
464       class VersionChecker extends Thread
465       {
466
467         @Override
468         public void run()
469         {
470           String buildPropertiesUrl = Cache.getAppbaseBuildProperties();
471
472           String orgtimeout = System
473                   .getProperty("sun.net.client.defaultConnectTimeout");
474           if (orgtimeout == null)
475           {
476             orgtimeout = "30";
477             System.out.println("# INFO: Setting default net timeout to "
478                     + orgtimeout + " seconds.");
479           }
480           String remoteVersion = null;
481           try
482           {
483             System.setProperty("sun.net.client.defaultConnectTimeout",
484                     "5000");
485             java.net.URL url = new java.net.URL(buildPropertiesUrl);
486
487             BufferedReader in = new BufferedReader(
488                     new InputStreamReader(url.openStream()));
489
490             Properties remoteBuildProperties = new Properties();
491             remoteBuildProperties.load(in);
492             remoteVersion = remoteBuildProperties.getProperty("VERSION");
493           } catch (Exception ex)
494           {
495             System.out
496                     .println("Non-fatal exception when checking version at "
497                             + buildPropertiesUrl + ":");
498             System.out.println(ex);
499             remoteVersion = getProperty("VERSION");
500           }
501           System.setProperty("sun.net.client.defaultConnectTimeout",
502                   orgtimeout);
503
504           setProperty("LATEST_VERSION", remoteVersion);
505         }
506       }
507
508       VersionChecker vc = new VersionChecker();
509       vc.start();
510     }
511     else
512     {
513       if (jnlpVersion != null)
514       {
515         setProperty("LATEST_VERSION", jnlpVersion);
516       }
517       else
518       {
519         applicationProperties.remove("LATEST_VERSION");
520       }
521     }
522
523     // LOAD USERDEFINED COLOURS
524     jalview.bin.Cache
525             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
526     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
527             false);
528   }
529
530   public static void loadBuildProperties(boolean reportVersion)
531   {
532     String codeInstallation = getProperty("INSTALLATION");
533     boolean printV = codeInstallation == null;
534
535     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
536     try
537     {
538       String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
539               .getCodeSource().getLocation().toString()
540               .concat("!/.build_properties"));
541
542       java.net.URL localJarFileURL = new java.net.URL(buildDetails);
543
544       InputStream in = localJarFileURL.openStream();
545       applicationProperties.load(in);
546       in.close();
547     } catch (Exception ex)
548     {
549       System.out.println("Error reading build details: " + ex);
550       applicationProperties.remove("VERSION");
551     }
552     String codeVersion = getProperty("VERSION");
553     codeInstallation = getProperty("INSTALLATION");
554
555     if (codeVersion == null)
556     {
557       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
558       codeVersion = "Test";
559       codeInstallation = "";
560     }
561     else
562     {
563       codeInstallation = " (" + codeInstallation + ")";
564     }
565     setProperty("VERSION", codeVersion);
566     new BuildDetails(codeVersion, null, codeInstallation);
567     if (printV && reportVersion)
568     {
569       System.out.println(
570               "Jalview Version: " + codeVersion + codeInstallation);
571     }
572   }
573
574   private static void deleteBuildProperties()
575   {
576     applicationProperties.remove("LATEST_VERSION");
577     applicationProperties.remove("VERSION");
578     applicationProperties.remove("AUTHORS");
579     applicationProperties.remove("AUTHORFNAMES");
580     applicationProperties.remove("YEAR");
581     applicationProperties.remove("BUILD_DATE");
582     applicationProperties.remove("INSTALLATION");
583   }
584
585   /**
586    * Gets Jalview application property of given key. Returns null if key not
587    * found
588    * 
589    * @param key
590    *          Name of property
591    * 
592    * @return Property value
593    */
594   public static String getProperty(String key)
595   {
596     return applicationProperties.getProperty(key);
597   }
598
599   /**
600    * These methods are used when checking if the saved preference is different
601    * to the default setting
602    */
603
604   public static boolean getDefault(String property, boolean def)
605   {
606     String string = getProperty(property);
607     if (string != null)
608     {
609       def = Boolean.valueOf(string).booleanValue();
610     }
611
612     return def;
613   }
614
615   public static int getDefault(String property, int def)
616   {
617     String string = getProperty(property);
618     if (string != null)
619     {
620       try
621       {
622         def = Integer.parseInt(string);
623       } catch (NumberFormatException e)
624       {
625         System.out.println("Error parsing int property '" + property
626                 + "' with value '" + string + "'");
627       }
628     }
629
630     return def;
631   }
632
633   /**
634    * These methods are used when checking if the saved preference is different
635    * to the default setting
636    */
637   public static String getDefault(String property, String def)
638   {
639     String string = getProperty(property);
640     if (string != null)
641     {
642       return string;
643     }
644
645     return def;
646   }
647
648   /**
649    * Stores property in the file "HOME_DIR/.jalview_properties"
650    * 
651    * @param key
652    *          Name of object
653    * @param obj
654    *          String value of property
655    * 
656    * @return previous value of property (or null)
657    */
658   public static Object setProperty(String key, String obj)
659   {
660     Object oldValue = null;
661     try
662     {
663       oldValue = applicationProperties.setProperty(key, obj);
664       if (propertiesFile != null && !propsAreReadOnly)
665       {
666         FileOutputStream out = new FileOutputStream(propertiesFile);
667         applicationProperties.store(out, "---JalviewX Properties File---");
668         out.close();
669       }
670     } catch (Exception ex)
671     {
672       System.out.println(
673               "Error setting property: " + key + " " + obj + "\n" + ex);
674     }
675     return oldValue;
676   }
677
678   /**
679    * remove the specified property from the jalview properties file
680    * 
681    * @param string
682    */
683   public static void removeProperty(String string)
684   {
685     applicationProperties.remove(string);
686     saveProperties();
687   }
688
689   /**
690    * save the properties to the jalview properties path
691    */
692   public static void saveProperties()
693   {
694     if (!propsAreReadOnly)
695     {
696       try
697       {
698         FileOutputStream out = new FileOutputStream(propertiesFile);
699         applicationProperties.store(out, "---JalviewX Properties File---");
700         out.close();
701       } catch (Exception ex)
702       {
703         System.out.println("Error saving properties: " + ex);
704       }
705     }
706   }
707
708   /**
709    * internal vamsas class discovery state
710    */
711   private static int vamsasJarsArePresent = -1;
712
713   /**
714    * Searches for vamsas client classes on class path.
715    * 
716    * @return true if vamsas client is present on classpath
717    */
718   public static boolean vamsasJarsPresent()
719   {
720     if (vamsasJarsArePresent == -1)
721     {
722       try
723       {
724         if (jalview.jbgui.GDesktop.class.getClassLoader()
725                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
726         {
727           jalview.bin.Cache.log.debug(
728                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
729           vamsasJarsArePresent = 1;
730           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
731           lvclient.setLevel(Level.toLevel(Cache
732                   .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
733
734           lvclient.addAppender(log.getAppender("JalviewLogger"));
735           // Tell the user that debug is enabled
736           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
737         }
738       } catch (Exception e)
739       {
740         vamsasJarsArePresent = 0;
741         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
742       }
743     }
744     return (vamsasJarsArePresent > 0);
745   }
746
747   /**
748    * internal vamsas class discovery state
749    */
750   private static int groovyJarsArePresent = -1;
751
752   /**
753    * Searches for vamsas client classes on class path.
754    * 
755    * @return true if vamsas client is present on classpath
756    */
757   public static boolean groovyJarsPresent()
758   {
759     if (groovyJarsArePresent == -1)
760     {
761       try
762       {
763         if (Cache.class.getClassLoader()
764                 .loadClass("groovy.lang.GroovyObject") != null)
765         {
766           jalview.bin.Cache.log.debug(
767                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
768           groovyJarsArePresent = 1;
769           Logger lgclient = Logger.getLogger("groovy");
770           lgclient.setLevel(Level.toLevel(Cache
771                   .getDefault("logs.Groovy.Level", Level.INFO.toString())));
772
773           lgclient.addAppender(log.getAppender("JalviewLogger"));
774           // Tell the user that debug is enabled
775           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
776         }
777       } catch (Error e)
778       {
779         groovyJarsArePresent = 0;
780         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
781       } catch (Exception e)
782       {
783         groovyJarsArePresent = 0;
784         jalview.bin.Cache.log.debug("Groovy Classes are not present");
785       }
786     }
787     return (groovyJarsArePresent > 0);
788   }
789
790   /**
791    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
792    * enabled.
793    */
794   protected static Object tracker = null;
795
796   protected static Class trackerfocus = null;
797
798   protected static Class jgoogleanalyticstracker = null;
799
800   /**
801    * Initialise the google tracker if it is not done already.
802    */
803   public static void initGoogleTracker()
804   {
805     if (tracker == null)
806     {
807       if (jgoogleanalyticstracker == null)
808       {
809         // try to get the tracker class
810         try
811         {
812           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
813                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
814           trackerfocus = Cache.class.getClassLoader()
815                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
816         } catch (Exception e)
817         {
818           log.debug(
819                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
820           tracker = null;
821           jgoogleanalyticstracker = null;
822           trackerfocus = null;
823           return;
824         }
825       }
826       // now initialise tracker
827       Exception re = null, ex = null;
828       Error err = null;
829       String vrs = "No Version Accessible";
830       try
831       {
832         // Google analytics tracking code for Library Finder
833         tracker = jgoogleanalyticstracker
834                 .getConstructor(new Class[]
835                 { String.class, String.class, String.class })
836                 .newInstance(new Object[]
837                 { "Jalview Desktop",
838                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
839                             + jalview.bin.Cache.getDefault("BUILD_DATE",
840                                     "unknown")),
841                     "UA-9060947-1" });
842         jgoogleanalyticstracker
843                 .getMethod("trackAsynchronously", new Class[]
844                 { trackerfocus })
845                 .invoke(tracker, new Object[]
846                 { trackerfocus.getConstructor(new Class[] { String.class })
847                         .newInstance(new Object[]
848                         { "Application Started." }) });
849       } catch (RuntimeException e)
850       {
851         re = e;
852       } catch (Exception e)
853       {
854         ex = e;
855       } catch (Error e)
856       {
857         err = e;
858       }
859       if (re != null || ex != null || err != null)
860       {
861         if (log != null)
862         {
863           if (re != null)
864           {
865             log.debug("Caught runtime exception in googletracker init:",
866                     re);
867           }
868           if (ex != null)
869           {
870             log.warn(
871                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
872                             + vrs,
873                     ex);
874           }
875           if (err != null)
876           {
877             log.error(
878                     "Whilst initing GoogleTracker for Jalview Desktop version "
879                             + vrs,
880                     err);
881           }
882         }
883         else
884         {
885           if (re != null)
886           {
887             System.err.println(
888                     "Debug: Caught runtime exception in googletracker init:"
889                             + vrs);
890             re.printStackTrace();
891           }
892           if (ex != null)
893           {
894             System.err.println(
895                     "Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
896                             + vrs);
897             ex.printStackTrace();
898           }
899
900           if (err != null)
901           {
902             System.err.println(
903                     "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
904                             + vrs);
905             err.printStackTrace();
906           }
907         }
908       }
909       else
910       {
911         log.debug("Successfully initialised tracker.");
912       }
913     }
914   }
915
916   /**
917    * get the user's default colour if available
918    * 
919    * @param property
920    * @param defcolour
921    * @return
922    */
923   public static Color getDefaultColour(String property, Color defcolour)
924   {
925     String colprop = getProperty(property);
926     if (colprop == null)
927     {
928       return defcolour;
929     }
930     Color col = ColorUtils.parseColourString(colprop);
931     if (col == null)
932     {
933       log.warn("Couldn't parse '" + colprop + "' as a colour for "
934               + property);
935     }
936     return (col == null) ? defcolour : col;
937   }
938
939   /**
940    * store a colour as a Jalview user default property
941    * 
942    * @param property
943    * @param colour
944    */
945   public static void setColourProperty(String property, Color colour)
946   {
947     setProperty(property, jalview.util.Format.getHexString(colour));
948   }
949
950   /**
951    * Stores a formatted date in a jalview property, using a fixed locale.
952    * 
953    * @param propertyName
954    * @param date
955    * @return the formatted date string
956    */
957   public static String setDateProperty(String propertyName, Date date)
958   {
959     String formatted = date_format.format(date);
960     setProperty(propertyName, formatted);
961     return formatted;
962   }
963
964   /**
965    * Reads a date stored in a Jalview property, parses it (using a fixed locale
966    * format) and returns as a Date, or null if parsing fails
967    * 
968    * @param propertyName
969    * @return
970    * 
971    */
972   public static Date getDateProperty(String propertyName)
973   {
974     String val = getProperty(propertyName);
975     if (val != null)
976     {
977       try
978       {
979         return date_format.parse(val);
980       } catch (Exception ex)
981       {
982         System.err.println("Invalid or corrupt date in property '"
983                 + propertyName + "' : value was '" + val + "'");
984       }
985     }
986     return null;
987   }
988
989   /**
990    * get and parse a property as an integer. send any parsing problems to
991    * System.err
992    * 
993    * @param property
994    * @return null or Integer
995    */
996   public static Integer getIntegerProperty(String property)
997   {
998     String val = getProperty(property);
999     if (val != null && (val = val.trim()).length() > 0)
1000     {
1001       try
1002       {
1003         return Integer.valueOf(val);
1004       } catch (NumberFormatException x)
1005       {
1006         System.err.println("Invalid integer in property '" + property
1007                 + "' (value was '" + val + "')");
1008       }
1009     }
1010     return null;
1011   }
1012
1013   /**
1014    * Set the specified value, or remove it if null or empty. Does not save the
1015    * properties file.
1016    * 
1017    * @param propName
1018    * @param value
1019    */
1020   public static void setOrRemove(String propName, String value)
1021   {
1022     if (propName == null)
1023     {
1024       return;
1025     }
1026     if (value == null || value.trim().length() < 1)
1027     {
1028       Cache.applicationProperties.remove(propName);
1029     }
1030     else
1031     {
1032       Cache.applicationProperties.setProperty(propName, value);
1033     }
1034   }
1035
1036   /**
1037    * Loads in user colour schemes from files.
1038    * 
1039    * @param files
1040    *          a '|'-delimited list of file paths
1041    */
1042   public static void initUserColourSchemes(String files)
1043   {
1044     if (files == null || files.length() == 0)
1045     {
1046       return;
1047     }
1048
1049     // In case colours can't be loaded, we'll remove them
1050     // from the default list here.
1051     StringBuffer coloursFound = new StringBuffer();
1052     StringTokenizer st = new StringTokenizer(files, "|");
1053     while (st.hasMoreElements())
1054     {
1055       String file = st.nextToken();
1056       try
1057       {
1058         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1059         if (ucs != null)
1060         {
1061           if (coloursFound.length() > 0)
1062           {
1063             coloursFound.append("|");
1064           }
1065           coloursFound.append(file);
1066           ColourSchemes.getInstance().registerColourScheme(ucs);
1067         }
1068       } catch (Exception ex)
1069       {
1070         System.out.println("Error loading User ColourFile\n" + ex);
1071       }
1072     }
1073     if (!files.equals(coloursFound.toString()))
1074     {
1075       if (coloursFound.toString().length() > 1)
1076       {
1077         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1078                 coloursFound.toString());
1079       }
1080       else
1081       {
1082         applicationProperties
1083                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1084       }
1085     }
1086   }
1087
1088   /**
1089    * Initial logging information helper for various versions output
1090    * 
1091    * @param prefix
1092    * @param value
1093    * @param defaultValue
1094    */
1095   private static void appendIfNotNull(StringBuilder sb, String prefix,
1096           String value, String suffix, String defaultValue)
1097   {
1098     if (value == null && defaultValue == null)
1099     {
1100       return;
1101     }
1102     String line = prefix + (value != null ? value : defaultValue) + suffix;
1103     sb.append(line);
1104   }
1105
1106   /**
1107    * 
1108    * @return Jalview version, build details and JVM platform version for console
1109    */
1110   public static String getVersionDetailsForConsole()
1111   {
1112     StringBuilder sb = new StringBuilder();
1113     sb.append("Jalview Version: ");
1114     sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1115     sb.append("\n");
1116     sb.append("Jalview Installation: ");
1117     sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1118     sb.append("\n");
1119     sb.append("Build Date: ");
1120     sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1121     sb.append("\n");
1122     sb.append("Java version: ");
1123     sb.append(System.getProperty("java.version"));
1124     sb.append("\n");
1125     sb.append(System.getProperty("os.arch"));
1126     sb.append(" ");
1127     sb.append(System.getProperty("os.name"));
1128     sb.append(" ");
1129     sb.append(System.getProperty("os.version"));
1130     sb.append("\n");
1131     appendIfNotNull(sb, "Install4j version: ",
1132             System.getProperty("sys.install4jVersion"), "\n", null);
1133     appendIfNotNull(sb, "Install4j template version: ",
1134             System.getProperty("installer_template_version"), "\n", null);
1135     appendIfNotNull(sb, "Launcher version: ",
1136             System.getProperty("launcher_version"), "\n", null);
1137     LookAndFeel laf = UIManager.getLookAndFeel();
1138     String lafName = laf == null ? "Not obtained" : laf.getName();
1139     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1140     sb.append("LookAndFeel: ");
1141     sb.append(lafName);
1142     sb.append(" (");
1143     sb.append(lafClass);
1144     sb.append(")\n");
1145     // Not displayed in release version ( determined by possible version number
1146     // regex 9[9.]*9[.-_a9]* )
1147     if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1148             jalview.bin.Cache.getDefault("VERSION", "TEST")))
1149     {
1150       appendIfNotNull(sb, "Getdown appdir: ",
1151               System.getProperty("getdownappdir"), "\n", null);
1152       appendIfNotNull(sb, "Getdown appbase: ",
1153               System.getProperty("getdownappbase"), "\n", null);
1154       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1155               "\n", "unknown");
1156     }
1157     return sb.toString();
1158   }
1159
1160   /**
1161    * 
1162    * @return build details as reported in splashscreen
1163    */
1164   public static String getBuildDetailsForSplash()
1165   {
1166     // consider returning more human friendly info
1167     // eg 'built from Source' or update channel
1168     return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1169   }
1170
1171   public static String getStackTraceString(Throwable t)
1172   {
1173     StringWriter sw = new StringWriter();
1174     PrintWriter pw = new PrintWriter(sw);
1175     t.printStackTrace(pw);
1176     return sw.toString();
1177   }
1178
1179   /**
1180    * Getdown appbase methods
1181    */
1182
1183   private static final String releaseAppbase;
1184
1185   private static String getdownAppbase;
1186
1187   private static String getdownDistDir;
1188
1189   static
1190   {
1191     Float specversion = Float
1192             .parseFloat(System.getProperty("java.specification.version"));
1193     releaseAppbase = (specversion < 9)
1194             ? "https://www.jalview.org/getdown/release/1.8"
1195             : "https://www.jalview.org/getdown/release/11";
1196   }
1197
1198   // look for properties (passed in by getdown) otherwise default to release
1199   private static void setGetdownAppbase()
1200   {
1201     if (getdownAppbase != null)
1202     {
1203       return;
1204     }
1205     String appbase = System.getProperty("getdownappbase");
1206     String distDir = System.getProperty("getdowndistdir");
1207     if (appbase == null)
1208     {
1209       appbase = releaseAppbase;
1210       distDir = "release";
1211     }
1212     if (appbase.endsWith("/"))
1213     {
1214       appbase = appbase.substring(0, appbase.length() - 1);
1215     }
1216     if (distDir == null)
1217     {
1218       distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1219     }
1220     getdownAppbase = appbase;
1221     getdownDistDir = distDir;
1222   }
1223
1224   public static String getGetdownAppbase()
1225   {
1226     setGetdownAppbase();
1227     return getdownAppbase;
1228   }
1229
1230   public static String getAppbaseBuildProperties()
1231   {
1232     String appbase = getGetdownAppbase();
1233     return appbase + "/" + getdownDistDir + "/build_properties";
1234   }
1235 }