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