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