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