JAL-1919 set default structure file format to mmCIF, refactored some StructureImportS...
[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     StructureImportSettings.setProcessHETATMs(jalview.bin.Cache.getDefault(
437             "PROCESS_HETATM", false));
438     // jnlpVersion will be null if we're using InstallAnywhere
439     // Dont do this check if running in headless mode
440     if (jnlpVersion == null
441             && getDefault("VERSION_CHECK", true)
442             && (System.getProperty("java.awt.headless") == null || System
443                     .getProperty("java.awt.headless").equals("false")))
444     {
445
446       class VersionChecker extends Thread
447       {
448         @Override
449         public void run()
450         {
451           String orgtimeout = System
452                   .getProperty("sun.net.client.defaultConnectTimeout");
453           if (orgtimeout == null)
454           {
455             orgtimeout = "30";
456             System.out.println("# INFO: Setting default net timeout to "
457                     + orgtimeout + " seconds.");
458           }
459           String remoteVersion = null;
460           try
461           {
462             System.setProperty("sun.net.client.defaultConnectTimeout",
463                     "5000");
464             java.net.URL url = new java.net.URL(Cache.getDefault(
465                     "www.jalview.org", "http://www.jalview.org")
466                     + "/webstart/jalview.jnlp");
467             BufferedReader in = new BufferedReader(new InputStreamReader(
468                     url.openStream()));
469             String line = null;
470             while ((line = in.readLine()) != null)
471             {
472               if (line.indexOf("jalview.version") == -1)
473               {
474                 continue;
475               }
476
477               line = line.substring(line.indexOf("value=") + 7);
478               line = line.substring(0, line.lastIndexOf("\""));
479               remoteVersion = line;
480               break;
481             }
482           } catch (Exception ex)
483           {
484             System.out
485                     .println("Non-fatal exception when checking version at www.jalview.org :");
486             System.out.println(ex);
487             remoteVersion = getProperty("VERSION");
488           }
489           System.setProperty("sun.net.client.defaultConnectTimeout",
490                   orgtimeout);
491
492           setProperty("LATEST_VERSION", remoteVersion);
493         }
494       }
495
496       VersionChecker vc = new VersionChecker();
497       vc.start();
498     }
499     else
500     {
501       if (jnlpVersion != null)
502       {
503         setProperty("LATEST_VERSION", jnlpVersion);
504       }
505       else
506       {
507         applicationProperties.remove("LATEST_VERSION");
508       }
509     }
510
511     setProperty("VERSION", codeVersion);
512
513     // LOAD USERDEFINED COLOURS
514     jalview.gui.UserDefinedColours
515             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
516     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
517             false);
518   }
519
520   private static void deleteBuildProperties()
521   {
522     applicationProperties.remove("LATEST_VERSION");
523     applicationProperties.remove("VERSION");
524     applicationProperties.remove("AUTHORS");
525     applicationProperties.remove("AUTHORFNAMES");
526     applicationProperties.remove("YEAR");
527     applicationProperties.remove("BUILD_DATE");
528     applicationProperties.remove("INSTALLATION");
529   }
530
531   /**
532    * Gets Jalview application property of given key. Returns null if key not
533    * found
534    * 
535    * @param key
536    *          Name of property
537    * 
538    * @return Property value
539    */
540   public static String getProperty(String key)
541   {
542     return applicationProperties.getProperty(key);
543   }
544
545   /**
546    * These methods are used when checking if the saved preference is different
547    * to the default setting
548    */
549
550   public static boolean getDefault(String property, boolean def)
551   {
552     String string = getProperty(property);
553     if (string != null)
554     {
555       def = Boolean.valueOf(string).booleanValue();
556     }
557
558     return def;
559   }
560
561   /**
562    * These methods are used when checking if the saved preference is different
563    * to the default setting
564    */
565   public static String getDefault(String property, String def)
566   {
567     String string = getProperty(property);
568     if (string != null)
569     {
570       return string;
571     }
572
573     return def;
574   }
575
576   /**
577    * Stores property in the file "HOME_DIR/.jalview_properties"
578    * 
579    * @param key
580    *          Name of object
581    * @param obj
582    *          String value of property
583    * 
584    * @return String value of property
585    */
586   public static String setProperty(String key, String obj)
587   {
588
589     try
590     {
591       applicationProperties.setProperty(key, obj);
592       if (!propsAreReadOnly)
593       {
594         FileOutputStream out = new FileOutputStream(propertiesFile);
595         applicationProperties.store(out, "---JalviewX Properties File---");
596         out.close();
597       }
598     } catch (Exception ex)
599     {
600       System.out.println("Error setting property: " + key + " " + obj
601               + "\n" + ex);
602     }
603     return obj;
604   }
605
606   /**
607    * remove the specified property from the jalview properties file
608    * 
609    * @param string
610    */
611   public static void removeProperty(String string)
612   {
613     applicationProperties.remove(string);
614     saveProperties();
615   }
616
617   /**
618    * save the properties to the jalview properties path
619    */
620   public static void saveProperties()
621   {
622     if (!propsAreReadOnly)
623     {
624       try
625       {
626         FileOutputStream out = new FileOutputStream(propertiesFile);
627         applicationProperties.store(out, "---JalviewX Properties File---");
628         out.close();
629       } catch (Exception ex)
630       {
631         System.out.println("Error saving properties: " + ex);
632       }
633     }
634   }
635
636   /**
637    * internal vamsas class discovery state
638    */
639   private static int vamsasJarsArePresent = -1;
640
641   /**
642    * Searches for vamsas client classes on class path.
643    * 
644    * @return true if vamsas client is present on classpath
645    */
646   public static boolean vamsasJarsPresent()
647   {
648     if (vamsasJarsArePresent == -1)
649     {
650       try
651       {
652         if (jalview.jbgui.GDesktop.class.getClassLoader().loadClass(
653                 "uk.ac.vamsas.client.VorbaId") != null)
654         {
655           jalview.bin.Cache.log
656                   .debug("Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
657           vamsasJarsArePresent = 1;
658           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
659           lvclient.setLevel(Level.toLevel(Cache.getDefault(
660                   "logs.Vamsas.Level", Level.INFO.toString())));
661
662           lvclient.addAppender(log.getAppender("JalviewLogger"));
663           // Tell the user that debug is enabled
664           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
665         }
666       } catch (Exception e)
667       {
668         vamsasJarsArePresent = 0;
669         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
670       }
671     }
672     return (vamsasJarsArePresent > 0);
673   }
674
675   /**
676    * internal vamsas class discovery state
677    */
678   private static int groovyJarsArePresent = -1;
679
680   /**
681    * Searches for vamsas client classes on class path.
682    * 
683    * @return true if vamsas client is present on classpath
684    */
685   public static boolean groovyJarsPresent()
686   {
687     if (groovyJarsArePresent == -1)
688     {
689       try
690       {
691         if (Cache.class.getClassLoader().loadClass(
692                 "groovy.lang.GroovyObject") != null)
693         {
694           jalview.bin.Cache.log
695                   .debug("Found Groovy (groovy.lang.GroovyObject can be loaded)");
696           groovyJarsArePresent = 1;
697           Logger lgclient = Logger.getLogger("groovy");
698           lgclient.setLevel(Level.toLevel(Cache.getDefault(
699                   "logs.Groovy.Level", Level.INFO.toString())));
700
701           lgclient.addAppender(log.getAppender("JalviewLogger"));
702           // Tell the user that debug is enabled
703           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
704         }
705       } catch (Error e)
706       {
707         groovyJarsArePresent = 0;
708         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
709       } catch (Exception e)
710       {
711         groovyJarsArePresent = 0;
712         jalview.bin.Cache.log.debug("Groovy Classes are not present");
713       }
714     }
715     return (groovyJarsArePresent > 0);
716   }
717
718   /**
719    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
720    * enabled.
721    */
722   protected static Object tracker = null;
723
724   protected static Class trackerfocus = null;
725
726   protected static Class jgoogleanalyticstracker = null;
727
728   /**
729    * Initialise the google tracker if it is not done already.
730    */
731   public static void initGoogleTracker()
732   {
733     if (tracker == null)
734     {
735       if (jgoogleanalyticstracker == null)
736       {
737         // try to get the tracker class
738         try
739         {
740           jgoogleanalyticstracker = Cache.class
741                   .getClassLoader()
742                   .loadClass(
743                           "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
744           trackerfocus = Cache.class.getClassLoader().loadClass(
745                   "com.boxysystems.jgoogleanalytics.FocusPoint");
746         } catch (Exception e)
747         {
748           log.debug("com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
749           tracker = null;
750           jgoogleanalyticstracker = null;
751           trackerfocus = null;
752           return;
753         }
754       }
755       // now initialise tracker
756       Exception re = null, ex = null;
757       Error err = null;
758       String vrs = "No Version Accessible";
759       try
760       {
761         // Google analytics tracking code for Library Finder
762         tracker = jgoogleanalyticstracker.getConstructor(
763                 new Class[] { String.class, String.class, String.class })
764                 .newInstance(
765                         new Object[] {
766                             "Jalview Desktop",
767                             (vrs = jalview.bin.Cache.getProperty("VERSION")
768                                     + "_"
769                                     + jalview.bin.Cache.getDefault(
770                                             "BUILD_DATE", "unknown")),
771                             "UA-9060947-1" });
772         jgoogleanalyticstracker.getMethod("trackAsynchronously",
773                 new Class[] { trackerfocus }).invoke(
774                 tracker,
775                 new Object[] { trackerfocus.getConstructor(
776                         new Class[] { String.class }).newInstance(
777                         new Object[] { "Application Started." }) });
778       } catch (RuntimeException e)
779       {
780         re = e;
781       } catch (Exception e)
782       {
783         ex = e;
784       } catch (Error e)
785       {
786         err = e;
787       }
788       if (re != null || ex != null || err != null)
789       {
790         if (log != null)
791         {
792           if (re != null)
793           {
794             log.debug("Caught runtime exception in googletracker init:", re);
795           }
796           if (ex != null)
797           {
798             log.warn(
799                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
800                             + vrs, ex);
801           }
802           if (err != null)
803           {
804             log.error(
805                     "Whilst initing GoogleTracker for Jalview Desktop version "
806                             + vrs, err);
807           }
808         }
809         else
810         {
811           if (re != null)
812           {
813             System.err
814                     .println("Debug: Caught runtime exception in googletracker init:"
815                             + vrs);
816             re.printStackTrace();
817           }
818           if (ex != null)
819           {
820             System.err
821                     .println("Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
822                             + vrs);
823             ex.printStackTrace();
824           }
825
826           if (err != null)
827           {
828             System.err
829                     .println("ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
830                             + vrs);
831             err.printStackTrace();
832           }
833         }
834       }
835       else
836       {
837         log.debug("Successfully initialised tracker.");
838       }
839     }
840   }
841
842   /**
843    * get the user's default colour if available
844    * 
845    * @param property
846    * @param defcolour
847    * @return
848    */
849   public static Color getDefaultColour(String property, Color defcolour)
850   {
851     String colprop = getProperty(property);
852     if (colprop == null)
853     {
854       return defcolour;
855     }
856     Color col = jalview.schemes.ColourSchemeProperty
857             .getAWTColorFromName(colprop);
858     if (col == null)
859     {
860       try
861       {
862         col = new jalview.schemes.UserColourScheme(colprop).findColour('A');
863       } catch (Exception ex)
864       {
865         log.warn("Couldn't parse '" + colprop + "' as a colour for "
866                 + property);
867         col = null;
868       }
869     }
870     return (col == null) ? defcolour : col;
871   }
872
873   /**
874    * store a colour as a Jalview user default property
875    * 
876    * @param property
877    * @param colour
878    */
879   public static void setColourProperty(String property, Color colour)
880   {
881     setProperty(property, jalview.util.Format.getHexString(colour));
882   }
883
884   public static final DateFormat date_format = SimpleDateFormat
885           .getDateTimeInstance();
886
887   /**
888    * store a date in a jalview property
889    * 
890    * @param string
891    * @param time
892    */
893   public static void setDateProperty(String property, Date time)
894   {
895     setProperty(property, date_format.format(time));
896   }
897
898   /**
899    * read a date stored in a jalview property
900    * 
901    * @param property
902    * @return valid date as stored by setDateProperty, or null
903    * 
904    */
905   public static Date getDateProperty(String property)
906   {
907     String val = getProperty(property);
908     if (val != null)
909     {
910       try
911       {
912         return date_format.parse(val);
913       } catch (Exception ex)
914       {
915         System.err.println("Invalid or corrupt date in property '"
916                 + property + "' : value was '" + val + "'");
917       }
918     }
919     return null;
920   }
921
922   /**
923    * get and parse a property as an integer. send any parsing problems to
924    * System.err
925    * 
926    * @param property
927    * @return null or Integer
928    */
929   public static Integer getIntegerProperty(String property)
930   {
931     String val = getProperty(property);
932     if (val != null && (val = val.trim()).length() > 0)
933     {
934       try
935       {
936         return Integer.valueOf(val);
937       } catch (NumberFormatException x)
938       {
939         System.err.println("Invalid integer in property '" + property
940                 + "' (value was '" + val + "')");
941       }
942     }
943     return null;
944   }
945
946   private static DasSourceRegistryI sourceRegistry = null;
947
948   /**
949    * initialise and ..
950    * 
951    * @return instance of the das source registry
952    */
953   public static DasSourceRegistryI getDasSourceRegistry()
954   {
955     if (sourceRegistry == null)
956     {
957       sourceRegistry = new DasSourceRegistry();
958     }
959     return sourceRegistry;
960   }
961
962   /**
963    * Set the specified value, or remove it if null or empty. Does not save the
964    * properties file.
965    * 
966    * @param propName
967    * @param value
968    */
969   public static void setOrRemove(String propName, String value)
970   {
971     if (propName == null)
972     {
973       return;
974     }
975     if (value == null || value.trim().length() < 1)
976     {
977       Cache.applicationProperties.remove(propName);
978     }
979     else
980     {
981       Cache.applicationProperties.setProperty(propName, value);
982     }
983   }
984 }