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