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