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