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