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