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