3dea84e53dff3cd11d1584f5ef0ba32062722f06
[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>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
154  * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
155  * warning dialog box is displayed.</li>
156  * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
157  * when shading by annotation</li>
158  * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
159  * when shading by annotation</li>
160  * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
161  * requests to be redirected to a mirror of http://www.jalview.org</li>
162  * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
163  * alignment figure to accommodate even the longest sequence ID or annotation
164  * label.</li>
165  * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
166  * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
167  * will override this).</li>
168  * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
169  * record</li>
170  * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
171  * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
172  * display</li>
173  * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
174  * display</li>
175  * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
176  * display</li>
177  * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
178  * 
179  * </ul>
180  * Deprecated settings:
181  * <ul>
182  * *
183  * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
184  * startup (JWS1 services only)</li>
185  * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
186  * (JWS1 services only)</li>
187  * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
188  * services in the desktop GUI</li>
189  * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
190  * panel in web service preferences</li>
191  * </ul>
192  * 
193  * @author $author$
194  * @version $Revision$
195  */
196 public class Cache
197 {
198   /**
199    * property giving log4j level for CASTOR loggers
200    */
201   public static final String CASTORLOGLEVEL = "logs.Castor.level";
202
203   /**
204    * property giving log4j level for AXIS loggers
205    */
206   public static final String AXISLOGLEVEL = "logs.Axis.level";
207
208   /**
209    * property giving log4j level for Jalview Log
210    */
211   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
212
213   public static final String DAS_LOCAL_SOURCE = "DAS_LOCAL_SOURCE";
214
215   public static final String DAS_REGISTRY_URL = "DAS_REGISTRY_URL";
216
217   public static final String DAS_ACTIVE_SOURCE = "DAS_ACTIVE_SOURCE";
218
219   /**
220    * Initialises the Jalview Application Log
221    */
222   public static Logger log;
223
224   /** Jalview Properties */
225   public static Properties applicationProperties = new Properties() {
226     // override results in properties output in alphabetical order
227     @Override
228     public synchronized Enumeration<Object> keys() {
229         return Collections.enumeration(new TreeSet<Object>(super.keySet()));
230     }
231   };
232
233   /** Default file is ~/.jalview_properties */
234   static String propertiesFile;
235
236   private static boolean propsAreReadOnly = false;
237
238   public static void initLogger()
239   {
240     if (log != null)
241     {
242       return;
243     }
244     try
245     {
246       // TODO: redirect stdout and stderr here in order to grab the output of
247       // the log
248
249       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
250               "System.err");
251       ap.setName("JalviewLogger");
252       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
253       // log output
254       Logger laxis = Logger.getLogger("org.apache.axis");
255       Logger lcastor = Logger.getLogger("org.exolab.castor");
256       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
257
258       laxis.setLevel(Level.toLevel(Cache.getDefault("logs.Axis.Level",
259               Level.INFO.toString())));
260       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
261               Level.INFO.toString())));
262       lcastor = Logger.getLogger("org.exolab.castor.xml");
263       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
264               Level.INFO.toString())));
265       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
266       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
267       // Level.INFO.toString())));
268       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache.getDefault(
269               "logs.Jalview.level", Level.INFO.toString())));
270       // laxis.addAppender(ap);
271       // lcastor.addAppender(ap);
272       // jalview.bin.Cache.log.addAppender(ap);
273       // Tell the user that debug is enabled
274       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
275     } catch (Exception ex)
276     {
277       System.err.println("Problems initializing the log4j system\n");
278       ex.printStackTrace(System.err);
279     }
280   }
281
282   /** Called when Jalview is started */
283   public static void loadProperties(String propsFile)
284   {
285     propertiesFile = propsFile;
286     if (propsFile == null)
287     {
288       propertiesFile = System.getProperty("user.home") + File.separatorChar
289               + ".jalview_properties";
290     }
291     else
292     {
293       // don't corrupt the file we've been given.
294       propsAreReadOnly = true;
295     }
296
297     try
298     {
299       InputStream fis;
300       try
301       {
302         fis = new java.net.URL(propertiesFile).openStream();
303         System.out.println("Loading jalview properties from : "
304                 + propertiesFile);
305         System.out
306                 .println("Disabling Jalview writing to user's local properties file.");
307         propsAreReadOnly = true;
308
309       } catch (Exception ex)
310       {
311         fis = null;
312       }
313       if (fis == null)
314       {
315         fis = new FileInputStream(propertiesFile);
316       }
317       applicationProperties.load(fis);
318       
319       // remove any old build properties
320       
321       deleteBuildProperties();
322       fis.close();
323     } catch (Exception ex)
324     {
325       System.out.println("Error reading properties file: " + ex);
326     }
327
328     if (getDefault("USE_PROXY", false))
329     {
330       String proxyServer = getDefault("PROXY_SERVER", ""), proxyPort = getDefault(
331               "PROXY_PORT", "8080");
332
333       System.out.println("Using proxyServer: " + proxyServer
334               + " proxyPort: " + proxyPort);
335
336       System.setProperty("http.proxyHost", proxyServer);
337       System.setProperty("http.proxyPort", proxyPort);
338     }
339
340     // LOAD THE AUTHORS FROM THE authors.props file
341     try
342     {
343       String authorDetails = "jar:".concat(Cache.class
344               .getProtectionDomain().getCodeSource().getLocation()
345               .toString().concat("!/authors.props"));
346
347       java.net.URL localJarFileURL = new java.net.URL(authorDetails);
348
349       InputStream in = localJarFileURL.openStream();
350       applicationProperties.load(in);
351       in.close();
352     } catch (Exception ex)
353     {
354       System.out.println("Error reading author details: " + ex);
355       applicationProperties.remove("AUTHORS");
356       applicationProperties.remove("AUTHORFNAMES");
357       applicationProperties.remove("YEAR");
358     }
359
360     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
361     // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
362     // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
363     try
364     {
365       String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
366               .getCodeSource().getLocation().toString()
367               .concat("!/.build_properties"));
368
369       java.net.URL localJarFileURL = new java.net.URL(buildDetails);
370
371       InputStream in = localJarFileURL.openStream();
372       applicationProperties.load(in);
373       in.close();
374     } catch (Exception ex)
375     {
376       System.out.println("Error reading build details: " + ex);
377       applicationProperties.remove("VERSION");
378     }
379
380     String jnlpVersion = System.getProperty("jalview.version");
381     String codeVersion = getProperty("VERSION");
382     String codeInstallation = getProperty("INSTALLATION");
383     if (codeVersion == null)
384     {
385       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
386       codeVersion = "Test";
387       jnlpVersion = "Test";
388       codeInstallation = "";
389     }
390     else
391     {
392       codeInstallation = " (" + codeInstallation + ")";
393     }
394
395     System.out
396             .println("Jalview Version: " + codeVersion + codeInstallation);
397
398     // jnlpVersion will be null if we're using InstallAnywhere
399     // Dont do this check if running in headless mode
400     if (jnlpVersion == null
401             && getDefault("VERSION_CHECK", true)
402             && (System.getProperty("java.awt.headless") == null || System
403                     .getProperty("java.awt.headless").equals("false")))
404     {
405
406       class VersionChecker extends Thread
407       {
408         public void run()
409         {
410           String orgtimeout = System
411                   .getProperty("sun.net.client.defaultConnectTimeout");
412           if (orgtimeout == null)
413           {
414             orgtimeout = "30";
415             System.out.println("# INFO: Setting default net timeout to "
416                     + orgtimeout + " seconds.");
417           }
418           String jnlpVersion = null;
419           try
420           {
421             System.setProperty("sun.net.client.defaultConnectTimeout",
422                     "5000");
423             java.net.URL url = new java.net.URL(Cache.getDefault(
424                     "www.jalview.org", "http://www.jalview.org")
425                     + "/webstart/jalview.jnlp");
426             BufferedReader in = new BufferedReader(new InputStreamReader(
427                     url.openStream()));
428             String line = null;
429             while ((line = in.readLine()) != null)
430             {
431               if (line.indexOf("jalview.version") == -1)
432               {
433                 continue;
434               }
435
436               line = line.substring(line.indexOf("value=") + 7);
437               line = line.substring(0, line.lastIndexOf("\""));
438               jnlpVersion = line;
439               break;
440             }
441           } catch (Exception ex)
442           {
443             System.out
444                     .println("Non-fatal exceptions when checking version at www.jalview.org :");
445             System.out.println(ex);
446             jnlpVersion = getProperty("VERSION");
447           }
448           System.setProperty("sun.net.client.defaultConnectTimeout",
449                   orgtimeout);
450
451           setProperty("LATEST_VERSION", jnlpVersion);
452         }
453       }
454
455       VersionChecker vc = new VersionChecker();
456       vc.start();
457     }
458     else
459     {
460       if (jnlpVersion != null)
461       {
462         setProperty("LATEST_VERSION", jnlpVersion);
463       }
464       else
465       {
466         applicationProperties.remove("LATEST_VERSION");
467       }
468     }
469
470     setProperty("VERSION", codeVersion);
471
472     // LOAD USERDEFINED COLOURS
473     jalview.gui.UserDefinedColours
474             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
475     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
476             false);
477   }
478
479   private static void deleteBuildProperties()
480   {
481     applicationProperties.remove("LATEST_VERSION");
482     applicationProperties.remove("VERSION");
483     applicationProperties.remove("AUTHORS");
484     applicationProperties.remove("AUTHORFNAMES");
485     applicationProperties.remove("YEAR");
486     applicationProperties.remove("BUILD_DATE");
487     applicationProperties.remove("INSTALLATION");
488   }
489
490   /**
491    * Gets Jalview application property of given key. Returns null if key not
492    * found
493    * 
494    * @param key
495    *          Name of property
496    * 
497    * @return Property value
498    */
499   public static String getProperty(String key)
500   {
501     return applicationProperties.getProperty(key);
502   }
503
504   /**
505    * These methods are used when checking if the saved preference is different
506    * to the default setting
507    */
508
509   public static boolean getDefault(String property, boolean def)
510   {
511     String string = getProperty(property);
512     if (string != null)
513     {
514       def = Boolean.valueOf(string).booleanValue();
515     }
516
517     return def;
518   }
519
520   /**
521    * These methods are used when checking if the saved preference is different
522    * to the default setting
523    */
524   public static String getDefault(String property, String def)
525   {
526     String string = getProperty(property);
527     if (string != null)
528     {
529       return string;
530     }
531
532     return def;
533   }
534
535   /**
536    * Stores property in the file "HOME_DIR/.jalview_properties"
537    * 
538    * @param key
539    *          Name of object
540    * @param obj
541    *          String value of property
542    * 
543    * @return String value of property
544    */
545   public static String setProperty(String key, String obj)
546   {
547
548     try
549     {
550       applicationProperties.setProperty(key, obj);
551       if (!propsAreReadOnly)
552       {
553         FileOutputStream out = new FileOutputStream(propertiesFile);
554         applicationProperties.store(out, "---JalviewX Properties File---");
555         out.close();
556       }
557     } catch (Exception ex)
558     {
559       System.out.println("Error setting property: " + key + " " + obj
560               + "\n" + ex);
561     }
562     return obj;
563   }
564
565   /**
566    * remove the specified property from the jalview properties file
567    * 
568    * @param string
569    */
570   public static void removeProperty(String string)
571   {
572     applicationProperties.remove(string);
573     saveProperties();
574   }
575
576   /**
577    * save the properties to the jalview properties path
578    */
579   public static void saveProperties()
580   {
581     if (!propsAreReadOnly)
582     {
583       try
584       {
585         FileOutputStream out = new FileOutputStream(propertiesFile);
586         applicationProperties.store(out, "---JalviewX Properties File---");
587         out.close();
588       } catch (Exception ex)
589       {
590         System.out.println("Error saving properties: " + ex);
591       }
592     }
593   }
594
595   /**
596    * internal vamsas class discovery state
597    */
598   private static int vamsasJarsArePresent = -1;
599
600   /**
601    * Searches for vamsas client classes on class path.
602    * 
603    * @return true if vamsas client is present on classpath
604    */
605   public static boolean vamsasJarsPresent()
606   {
607     if (vamsasJarsArePresent == -1)
608     {
609       try
610       {
611         if (jalview.jbgui.GDesktop.class.getClassLoader().loadClass(
612                 "uk.ac.vamsas.client.VorbaId") != null)
613         {
614           jalview.bin.Cache.log
615                   .debug("Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
616           vamsasJarsArePresent = 1;
617           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
618           lvclient.setLevel(Level.toLevel(Cache.getDefault(
619                   "logs.Vamsas.Level", Level.INFO.toString())));
620
621           lvclient.addAppender(log.getAppender("JalviewLogger"));
622           // Tell the user that debug is enabled
623           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
624         }
625       } catch (Exception e)
626       {
627         vamsasJarsArePresent = 0;
628         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
629       }
630     }
631     return (vamsasJarsArePresent > 0);
632   }
633
634   /**
635    * internal vamsas class discovery state
636    */
637   private static int groovyJarsArePresent = -1;
638
639   /**
640    * Searches for vamsas client classes on class path.
641    * 
642    * @return true if vamsas client is present on classpath
643    */
644   public static boolean groovyJarsPresent()
645   {
646     if (groovyJarsArePresent == -1)
647     {
648       try
649       {
650         if (Cache.class.getClassLoader().loadClass(
651                 "groovy.lang.GroovyObject") != null)
652         {
653           jalview.bin.Cache.log
654                   .debug("Found Groovy (groovy.lang.GroovyObject can be loaded)");
655           groovyJarsArePresent = 1;
656           Logger lgclient = Logger.getLogger("groovy");
657           lgclient.setLevel(Level.toLevel(Cache.getDefault(
658                   "logs.Groovy.Level", Level.INFO.toString())));
659
660           lgclient.addAppender(log.getAppender("JalviewLogger"));
661           // Tell the user that debug is enabled
662           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
663         }
664       } catch (Error e)
665       {
666         groovyJarsArePresent = 0;
667         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
668       } catch (Exception e)
669       {
670         groovyJarsArePresent = 0;
671         jalview.bin.Cache.log.debug("Groovy Classes are not present");
672       }
673     }
674     return (groovyJarsArePresent > 0);
675   }
676
677   /**
678    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
679    * enabled.
680    */
681   protected static Object tracker = null;
682
683   protected static Class trackerfocus = null;
684
685   protected static Class jgoogleanalyticstracker = null;
686
687   /**
688    * Initialise the google tracker if it is not done already.
689    */
690   public static void initGoogleTracker()
691   {
692     if (tracker == null)
693     {
694       if (jgoogleanalyticstracker == null)
695       {
696         // try to get the tracker class
697         try
698         {
699           jgoogleanalyticstracker = Cache.class
700                   .getClassLoader()
701                   .loadClass(
702                           "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
703           trackerfocus = Cache.class.getClassLoader().loadClass(
704                   "com.boxysystems.jgoogleanalytics.FocusPoint");
705         } catch (Exception e)
706         {
707           log.debug("com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
708           tracker = null;
709           jgoogleanalyticstracker = null;
710           trackerfocus = null;
711           return;
712         }
713       }
714       // now initialise tracker
715       Exception re = null, ex = null;
716       Error err = null;
717       String vrs = "No Version Accessible";
718       try
719       {
720         // Google analytics tracking code for Library Finder
721         tracker = jgoogleanalyticstracker.getConstructor(new Class[]
722         { String.class, String.class, String.class }).newInstance(
723                 new Object[]
724                 {
725                     "Jalview Desktop",
726                     (vrs = jalview.bin.Cache.getProperty("VERSION")
727                             + "_"
728                             + jalview.bin.Cache.getDefault("BUILD_DATE",
729                                     "unknown")), "UA-9060947-1" });
730         jgoogleanalyticstracker.getMethod("trackAsynchronously",
731                 new Class[]
732                 { trackerfocus }).invoke(tracker, new Object[]
733         { trackerfocus.getConstructor(new Class[]
734         { String.class }).newInstance(new Object[]
735         { "Application Started." }) });
736       } catch (RuntimeException e)
737       {
738         re = e;
739       } catch (Exception e)
740       {
741         ex = e;
742       } catch (Error e)
743       {
744         err = e;
745       }
746       if (re != null || ex != null || err != null)
747       {
748         if (log != null)
749         {
750           if (re != null)
751           {
752             log.debug("Caught runtime exception in googletracker init:", re);
753           }
754           if (ex != null)
755           {
756             log.warn(
757                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
758                             + vrs, ex);
759           }
760           if (err != null)
761           {
762             log.error(
763                     "Whilst initing GoogleTracker for Jalview Desktop version "
764                             + vrs, err);
765           }
766         }
767         else
768         {
769           if (re != null)
770           {
771             System.err
772                     .println("Debug: Caught runtime exception in googletracker init:"
773                             + vrs);
774             re.printStackTrace();
775           }
776           if (ex != null)
777           {
778             System.err
779                     .println("Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
780                             + vrs);
781             ex.printStackTrace();
782           }
783
784           if (err != null)
785           {
786             System.err
787                     .println("ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
788                             + vrs);
789             err.printStackTrace();
790           }
791         }
792       }
793       else
794       {
795         log.debug("Successfully initialised tracker.");
796       }
797     }
798   }
799
800   /**
801    * get the user's default colour if available
802    * 
803    * @param property
804    * @param defcolour
805    * @return
806    */
807   public static Color getDefaultColour(String property, Color defcolour)
808   {
809     String colprop = getProperty(property);
810     if (colprop == null)
811     {
812       return defcolour;
813     }
814     Color col = jalview.schemes.ColourSchemeProperty
815             .getAWTColorFromName(colprop);
816     if (col == null)
817     {
818       try
819       {
820         col = new jalview.schemes.UserColourScheme(colprop).findColour('A');
821       } catch (Exception ex)
822       {
823         log.warn("Couldn't parse '" + colprop + "' as a colour for "
824                 + property);
825         col = null;
826       }
827     }
828     return (col == null) ? defcolour : col;
829   }
830
831   /**
832    * store a colour as a Jalview user default property
833    * 
834    * @param property
835    * @param colour
836    */
837   public static void setColourProperty(String property, Color colour)
838   {
839     setProperty(property, jalview.util.Format.getHexString(colour));
840   }
841
842   public static final DateFormat date_format = SimpleDateFormat
843           .getDateTimeInstance();
844
845   /**
846    * store a date in a jalview property
847    * 
848    * @param string
849    * @param time
850    */
851   public static void setDateProperty(String property, Date time)
852   {
853     setProperty(property, date_format.format(time));
854   }
855
856   /**
857    * read a date stored in a jalview property
858    * 
859    * @param property
860    * @return valid date as stored by setDateProperty, or null
861    * 
862    */
863   public static Date getDateProperty(String property)
864   {
865     String val = getProperty(property);
866     if (val != null)
867     {
868       try
869       {
870         return date_format.parse(val);
871       } catch (Exception ex)
872       {
873         System.err.println("Invalid or corrupt date in property '"
874                 + property + "' : value was '" + val + "'");
875       }
876     }
877     return null;
878   }
879
880   /**
881    * get and parse a property as an integer. send any parsing problems to
882    * System.err
883    * 
884    * @param property
885    * @return null or Integer
886    */
887   public static Integer getIntegerProperty(String property)
888   {
889     String val = getProperty(property);
890     if (val != null && (val = val.trim()).length() > 0)
891     {
892       try
893       {
894         return Integer.valueOf(val);
895       } catch (NumberFormatException x)
896       {
897         System.err.println("Invalid integer in property '" + property
898                 + "' (value was '" + val + "')");
899       }
900     }
901     return null;
902   }
903
904   private static DasSourceRegistryI sourceRegistry = null;
905
906   /**
907    * initialise and ..
908    * 
909    * @return instance of the das source registry
910    */
911   public static DasSourceRegistryI getDasSourceRegistry()
912   {
913     if (sourceRegistry == null)
914     {
915       sourceRegistry = new DasSourceRegistry();
916     }
917     return sourceRegistry;
918   }
919
920   /**
921    * Set the specified value, or remove it if null or empty. Does not save the
922    * properties file.
923    * 
924    * @param propName
925    * @param value
926    */
927   public static void setOrRemove(String propName, String value)
928   {
929     if (propName == null)
930     {
931       return;
932     }
933     if (value == null || value.trim().length() < 1)
934     {
935       Cache.applicationProperties.remove(propName);
936     }
937     else
938     {
939       Cache.applicationProperties.setProperty(propName, value);
940     }
941   }
942 }