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