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