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