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