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