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