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