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