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