JAL-3446 from JAL-3253 ApplicationSingletonProvider 1/many
[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 = System
251           .getProperty("user.home") + File.separatorChar
252           + ".sifts_downloads" + File.separatorChar;
253
254   private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
255
256   private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
257
258   /**
259    * Identifiers.org download settings
260    */
261   private static final String ID_ORG_FILE = System.getProperty("user.home")
262           + File.separatorChar + ".identifiers.org.ids.json";
263
264   /**
265    * Allowed values are PDB or mmCIF
266    */
267   private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
268           .toString();
269
270   private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
271           .toString();
272
273   /*
274    * a date formatter using a fixed (rather than the user's) locale; 
275    * this ensures that date properties can be written and re-read successfully
276    * even if the user changes their locale setting
277    */
278   private static final DateFormat date_format = SimpleDateFormat
279           .getDateTimeInstance(SimpleDateFormat.MEDIUM,
280                   SimpleDateFormat.MEDIUM, Locale.UK);
281
282   /**
283    * Initialises the Jalview Application Log
284    */
285   public static Logger log;
286
287   /** Jalview Properties */
288   private Properties applicationProperties = new Properties()
289   {
290     // override results in properties output in alphabetical order
291     @Override
292     public synchronized Enumeration<Object> keys()
293     {
294       return Collections.enumeration(new TreeSet<>(super.keySet()));
295     }
296   };
297
298   /** Default file is ~/.jalview_properties */
299   static String propertiesFile;
300
301   private static boolean propsAreReadOnly = Platform.isJS();
302
303   private final static String JS_PROPERTY_PREFIX = "jalview_";
304
305   public static void initLogger()
306   {
307     if (log != null)
308     {
309       return;
310     }
311     try
312     {
313       // TODO: redirect stdout and stderr here in order to grab the output of
314       // the log
315
316       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
317               "System.err");
318       ap.setName("JalviewLogger");
319       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
320       // log output
321       Logger laxis = Logger.getLogger("org.apache.axis");
322       Logger lcastor = Logger.getLogger("org.exolab.castor");
323       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
324
325       laxis.setLevel(Level.toLevel(
326               Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
327       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
328               Level.INFO.toString())));
329       lcastor = Logger.getLogger("org.exolab.castor.xml");
330       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
331               Level.INFO.toString())));
332       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
333       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
334       // Level.INFO.toString())));
335       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
336               .getDefault("logs.Jalview.level", Level.INFO.toString())));
337       // laxis.addAppender(ap);
338       // lcastor.addAppender(ap);
339       // jalview.bin.Cache.log.addAppender(ap);
340       // Tell the user that debug is enabled
341       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
342     } catch (Exception ex)
343     {
344       System.err.println("Problems initializing the log4j system\n");
345       ex.printStackTrace(System.err);
346     }
347   }
348
349   /**
350    * Loads properties from the given properties file. Any existing properties
351    * are first cleared.
352    */
353   public static void loadProperties(String propsFile)
354   {
355
356     getInstance().loadPropertiesImpl(propsFile);
357
358   }
359
360   private void loadPropertiesImpl(String propsFile)
361   {
362
363     propertiesFile = propsFile;
364     if (propsFile == null && !propsAreReadOnly)
365     {
366       propertiesFile = System.getProperty("user.home") + File.separatorChar
367               + ".jalview_properties";
368     }
369     else
370     {
371       // don't corrupt the file we've been given.
372       propsAreReadOnly = true;
373     }
374
375     if (propertiesFile == null)
376     { // BH 2019
377       Platform.readInfoProperties(JS_PROPERTY_PREFIX,
378               applicationProperties);
379     }
380     else
381     {
382       try
383       {
384         InputStream fis;
385         try
386         {
387           fis = new java.net.URL(propertiesFile).openStream();
388           System.out.println(
389                   "Loading jalview properties from : " + propertiesFile);
390           System.out.println(
391                   "Disabling Jalview writing to user's local properties file.");
392           propsAreReadOnly = true;
393
394         } catch (Exception ex)
395         {
396           fis = null;
397         }
398         if (fis == null)
399         {
400           fis = new FileInputStream(propertiesFile);
401         }
402         applicationProperties.clear();
403         applicationProperties.load(fis);
404
405         // remove any old build properties
406
407         deleteBuildProperties();
408         fis.close();
409       } catch (Exception ex)
410       {
411         System.out.println("Error reading properties file: " + ex);
412       }
413     }
414     if (getDefault("USE_PROXY", false))
415     {
416       String proxyServer = getDefault("PROXY_SERVER", ""),
417               proxyPort = getDefault("PROXY_PORT", "8080");
418
419       System.out.println("Using proxyServer: " + proxyServer
420               + " proxyPort: " + proxyPort);
421
422       System.setProperty("http.proxyHost", proxyServer);
423       System.setProperty("http.proxyPort", proxyPort);
424     }
425
426     // LOAD THE AUTHORS FROM THE authors.props file
427     String authorDetails = resolveResourceURLFor("/authors.props");
428
429     try
430     {
431       if (authorDetails != null)
432       {
433         URL localJarFileURL = new URL(authorDetails);
434         InputStream in = localJarFileURL.openStream();
435         applicationProperties.load(in);
436         in.close();
437       }
438     } catch (Exception ex)
439     {
440       System.out.println("Error reading author details: " + ex);
441       authorDetails = null;
442     }
443     if (authorDetails == null)
444     {
445       applicationProperties.remove("AUTHORS");
446       applicationProperties.remove("AUTHORFNAMES");
447       applicationProperties.remove("YEAR");
448     }
449
450     loadBuildProperties(false);
451
452     SiftsSettings
453             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
454
455     SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
456             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
457
458     SiftsSettings.setFailSafePIDThreshold(
459             jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
460                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
461
462     SiftsSettings.setCacheThresholdInDays(
463             jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
464                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
465
466     IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
467             "http://www.jalview.org/services/identifiers"));
468     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
469
470     StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
471             .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
472     StructureImportSettings
473             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
474     // StructureImportSettings
475     // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
476     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
477
478     String jnlpVersion = System.getProperty("jalview.version");
479
480     // jnlpVersion will be null if a latest version check for the channel needs
481     // to
482     // be done
483     // Dont do this check if running in headless mode
484
485     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
486             && (System.getProperty("java.awt.headless") == null || System
487                     .getProperty("java.awt.headless").equals("false")))
488     {
489       new Thread()
490       {
491         @Override
492         public void run()
493         {
494           String orgtimeout = System
495                   .getProperty("sun.net.client.defaultConnectTimeout");
496           if (orgtimeout == null)
497           {
498             orgtimeout = "30";
499             System.out.println("# INFO: Setting default net timeout to "
500                     + orgtimeout + " seconds.");
501           }
502           String remoteVersion = null;
503           try
504           {
505             System.setProperty("sun.net.client.defaultConnectTimeout",
506                     "5000");
507             java.net.URL url = new java.net.URL(Cache
508                     .getDefault("www.jalview.org", "http://www.jalview.org")
509                     + "/webstart/jalview.jnlp");
510             BufferedReader in = new BufferedReader(
511                     new InputStreamReader(url.openStream()));
512             String line = null;
513             while ((line = in.readLine()) != null)
514             {
515               if (line.indexOf("jalview.version") == -1)
516               {
517                 continue;
518               }
519
520               line = line.substring(line.indexOf("value=") + 7);
521               line = line.substring(0, line.lastIndexOf("\""));
522               remoteVersion = line;
523               break;
524             }
525           } catch (Exception ex)
526           {
527             System.out.println(
528                     "Non-fatal exception when checking version at www.jalview.org :");
529             System.out.println(ex);
530             remoteVersion = getProperty("VERSION");
531           }
532           System.setProperty("sun.net.client.defaultConnectTimeout",
533                   orgtimeout);
534
535           setProperty("LATEST_VERSION", remoteVersion);
536         }
537       }.start();
538     }
539     else
540     {
541       if (jnlpVersion != null)
542       {
543         setProperty("LATEST_VERSION", jnlpVersion);
544       }
545       else
546       {
547         applicationProperties.remove("LATEST_VERSION");
548       }
549     }
550
551     // LOAD USERDEFINED COLOURS
552     Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
553     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
554             false);
555   }
556
557   /**
558    * construct a resource URL for the given absolute resource pathname
559    * 
560    * @param resourcePath
561    * @return
562    */
563   private static String resolveResourceURLFor(String resourcePath)
564   {
565     String url = null;
566     if (Platform.isJS() || !Cache.class.getProtectionDomain()
567             .getCodeSource().getLocation().toString().endsWith(".jar"))
568     {
569       try
570       {
571         url = Cache.class.getResource(resourcePath).toString();
572       } catch (Exception ex)
573       {
574         System.err.println("Failed to resolve resource " + resourcePath
575                 + ": " + ex.getMessage());
576       }
577     }
578     else
579     {
580       url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
581               .getLocation().toString().concat("!" + resourcePath));
582     }
583     return url;
584   }
585
586   public void loadBuildProperties(boolean reportVersion)
587   {
588     String codeInstallation = getProperty("INSTALLATION");
589     boolean printVersion = codeInstallation == null;
590
591     /*
592      * read build properties - from the Jalview jar for a Java distribution,
593      * or from codebase file in test or JalviewJS context
594      */
595     try
596     {
597       String buildDetails = resolveResourceURLFor("/.build_properties");
598       URL localJarFileURL = new URL(buildDetails);
599       InputStream in = localJarFileURL.openStream();
600       applicationProperties.load(in);
601       in.close();
602     } catch (Exception ex)
603     {
604       System.out.println("Error reading build details: " + ex);
605       applicationProperties.remove("VERSION");
606     }
607     String codeVersion = getProperty("VERSION");
608     codeInstallation = getProperty("INSTALLATION");
609
610     if (codeVersion == null)
611     {
612       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
613       codeVersion = "Test";
614       codeInstallation = "";
615     }
616     else
617     {
618       codeInstallation = " (" + codeInstallation + ")";
619     }
620     setProperty("VERSION", codeVersion);
621     new BuildDetails(codeVersion, null, codeInstallation);
622     if (printVersion && reportVersion)
623     {
624       System.out.println(
625               "Jalview Version: " + codeVersion + codeInstallation);
626     }
627   }
628
629   private void deleteBuildProperties()
630   {
631     applicationProperties.remove("LATEST_VERSION");
632     applicationProperties.remove("VERSION");
633     applicationProperties.remove("AUTHORS");
634     applicationProperties.remove("AUTHORFNAMES");
635     applicationProperties.remove("YEAR");
636     applicationProperties.remove("BUILD_DATE");
637     applicationProperties.remove("INSTALLATION");
638   }
639
640   /**
641    * Gets Jalview application property of given key. Returns null if key not
642    * found
643    * 
644    * @param key
645    *          Name of property
646    * 
647    * @return Property value
648    */
649   public static String getProperty(String key)
650   {
651     String prop = getInstance().applicationProperties.getProperty(key);
652     // if (prop == null && Platform.isJS())
653     // {
654     // prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
655     // + "_" + JS_PROPERTY_PREFIX + key);
656     // }
657     return prop;
658   }
659
660   /**
661    * These methods are used when checking if the saved preference is different
662    * to the default setting
663    */
664
665   public static boolean getDefault(String property, boolean def)
666   {
667     String string = getProperty(property);
668     if (string != null)
669     {
670       def = Boolean.valueOf(string).booleanValue();
671     }
672
673     return def;
674   }
675
676   public static int getDefault(String property, int def)
677   {
678     String string = getProperty(property);
679     if (string != null)
680     {
681       try
682       {
683         def = Integer.parseInt(string);
684       } catch (NumberFormatException e)
685       {
686         System.out.println("Error parsing int property '" + property
687                 + "' with value '" + string + "'");
688       }
689     }
690
691     return def;
692   }
693
694   /**
695    * Answers the value of the given property, or the supplied default value if
696    * the property is not set
697    */
698   public static String getDefault(String property, String def)
699   {
700     String value = getProperty(property);
701     return value == null ? def : value;
702   }
703
704   /**
705    * Stores property in the file "HOME_DIR/.jalview_properties"
706    * 
707    * @param key
708    *          Name of object
709    * @param obj
710    *          String value of property
711    * 
712    * @return previous value of property (or null)
713    */
714   public static Object setProperty(String key, String obj)
715   {
716     return getInstance().setPropertyImpl(key, obj, true);
717   }
718
719   /**
720    * Removes the specified property from the jalview properties file
721    * 
722    * @param key
723    */
724   public static void removeProperty(String key)
725   {
726     getInstance().removePropertyImpl(key, true);
727   }
728
729   /**
730    * Removes the named property for the running application, without saving the
731    * properties file
732    * 
733    * BH noting that ColourMenuHelper calls this. If the intent is to save, then
734    * simply chanet that call to removeProperty(key).
735    * 
736    * @param key
737    */
738   public static void removePropertyNoSave(String key)
739   {
740
741     getInstance().
742
743             removePropertyImpl(key, false);
744   }
745
746   /**
747    * Removes the named property, and optionally saves the current properties to
748    * file
749    * 
750    * @param key
751    * @param andSave
752    */
753   private void removePropertyImpl(String key, boolean andSave)
754   {
755     applicationProperties.remove(key);
756     if (andSave)
757       saveProperties();
758   }
759
760   /**
761    * save the properties to the jalview properties path
762    */
763   public static void saveProperties()
764   {
765     getInstance().savePropertiesImpl();
766   }
767
768   /**
769    * save the properties to the jalview properties path
770    */
771   private void savePropertiesImpl()
772
773   {
774     if (!propsAreReadOnly)
775     {
776       try
777       {
778         FileOutputStream out = new FileOutputStream(propertiesFile);
779         applicationProperties.store(out, "---JalviewX Properties File---");
780         out.close();
781       } catch (Exception ex)
782       {
783         System.out.println("Error saving properties: " + ex);
784       }
785     }
786   }
787
788   /**
789    * internal vamsas class discovery state
790    */
791   private static int vamsasJarsArePresent = -1;
792
793   /**
794    * Searches for vamsas client classes on class path.
795    * 
796    * @return true if vamsas client is present on classpath
797    */
798   public static boolean vamsasJarsPresent()
799   {
800     if (vamsasJarsArePresent == -1)
801     {
802       try
803       {
804         if (jalview.jbgui.GDesktop.class.getClassLoader()
805                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
806         {
807           jalview.bin.Cache.log.debug(
808                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
809           vamsasJarsArePresent = 1;
810           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
811           lvclient.setLevel(Level.toLevel(Cache
812                   .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
813
814           lvclient.addAppender(log.getAppender("JalviewLogger"));
815           // Tell the user that debug is enabled
816           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
817         }
818       } catch (Exception e)
819       {
820         vamsasJarsArePresent = 0;
821         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
822       }
823     }
824     return (vamsasJarsArePresent > 0);
825   }
826
827   /**
828    * internal vamsas class discovery state
829    */
830   private static int groovyJarsArePresent = -1;
831
832   /**
833    * Searches for vamsas client classes on class path.
834    * 
835    * @return true if vamsas client is present on classpath
836    */
837   public static boolean groovyJarsPresent()
838   {
839     if (groovyJarsArePresent == -1)
840     {
841       try
842       {
843         if (Cache.class.getClassLoader()
844                 .loadClass("groovy.lang.GroovyObject") != null)
845         {
846           jalview.bin.Cache.log.debug(
847                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
848           groovyJarsArePresent = 1;
849           Logger lgclient = Logger.getLogger("groovy");
850           lgclient.setLevel(Level.toLevel(Cache
851                   .getDefault("logs.Groovy.Level", Level.INFO.toString())));
852
853           lgclient.addAppender(log.getAppender("JalviewLogger"));
854           // Tell the user that debug is enabled
855           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
856         }
857       } catch (Error e)
858       {
859         groovyJarsArePresent = 0;
860         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
861       } catch (Exception e)
862       {
863         groovyJarsArePresent = 0;
864         jalview.bin.Cache.log.debug("Groovy Classes are not present");
865       }
866     }
867     return (groovyJarsArePresent > 0);
868   }
869
870   /**
871    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
872    * enabled.
873    */
874   protected static Object tracker = null;
875
876   protected static Class trackerfocus = null;
877
878   protected static Class jgoogleanalyticstracker = null;
879
880   /**
881    * Initialise the google tracker if it is not done already.
882    */
883   public static void initGoogleTracker()
884   {
885     if (tracker == null)
886     {
887       if (jgoogleanalyticstracker == null)
888       {
889         // try to get the tracker class
890         try
891         {
892           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
893                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
894           trackerfocus = Cache.class.getClassLoader()
895                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
896         } catch (Exception e)
897         {
898           log.debug(
899                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
900           tracker = null;
901           jgoogleanalyticstracker = null;
902           trackerfocus = null;
903           return;
904         }
905       }
906       // now initialise tracker
907       Exception re = null, ex = null;
908       Error err = null;
909       String vrs = "No Version Accessible";
910       try
911       {
912         // Google analytics tracking code for Library Finder
913         tracker = jgoogleanalyticstracker
914                 .getConstructor(new Class[]
915                 { String.class, String.class, String.class })
916                 .newInstance(new Object[]
917                 { "Jalview Desktop",
918                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
919                             + jalview.bin.Cache.getDefault("BUILD_DATE",
920                                     "unknown")),
921                     "UA-9060947-1" });
922         jgoogleanalyticstracker
923                 .getMethod("trackAsynchronously", new Class[]
924                 { trackerfocus })
925                 .invoke(tracker, new Object[]
926                 { trackerfocus.getConstructor(new Class[] { String.class })
927                         .newInstance(new Object[]
928                         { "Application Started." }) });
929       } catch (RuntimeException e)
930       {
931         re = e;
932       } catch (Exception e)
933       {
934         ex = e;
935       } catch (Error e)
936       {
937         err = e;
938       }
939       if (re != null || ex != null || err != null)
940       {
941         if (log != null)
942         {
943           if (re != null)
944           {
945             log.debug("Caught runtime exception in googletracker init:",
946                     re);
947           }
948           if (ex != null)
949           {
950             log.warn(
951                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
952                             + vrs,
953                     ex);
954           }
955           if (err != null)
956           {
957             log.error(
958                     "Whilst initing GoogleTracker for Jalview Desktop version "
959                             + vrs,
960                     err);
961           }
962         }
963         else
964         {
965           if (re != null)
966           {
967             System.err.println(
968                     "Debug: Caught runtime exception in googletracker init:"
969                             + vrs);
970             re.printStackTrace();
971           }
972           if (ex != null)
973           {
974             System.err.println(
975                     "Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
976                             + vrs);
977             ex.printStackTrace();
978           }
979
980           if (err != null)
981           {
982             System.err.println(
983                     "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
984                             + vrs);
985             err.printStackTrace();
986           }
987         }
988       }
989       else
990       {
991         log.debug("Successfully initialised tracker.");
992       }
993     }
994   }
995
996   /**
997    * get the user's default colour if available
998    * 
999    * @param property
1000    * @param defcolour
1001    * @return
1002    */
1003   public static Color getDefaultColour(String property, Color defcolour)
1004   {
1005     String colprop = getProperty(property);
1006     if (colprop == null)
1007     {
1008       return defcolour;
1009     }
1010     Color col = ColorUtils.parseColourString(colprop);
1011     if (col == null)
1012     {
1013       log.warn("Couldn't parse '" + colprop + "' as a colour for "
1014               + property);
1015     }
1016     return (col == null) ? defcolour : col;
1017   }
1018
1019   /**
1020    * store a colour as a Jalview user default property
1021    * 
1022    * @param property
1023    * @param colour
1024    */
1025   public static void setColourPropertyNoSave(String property, Color colour)
1026   {
1027     setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
1028   }
1029
1030   /**
1031    * Stores a formatted date in a jalview property, using a fixed locale.
1032    * 
1033    * @param propertyName
1034    * @param date
1035    * @return the formatted date string
1036    */
1037   public static String setDateProperty(String propertyName, Date date)
1038   {
1039     String formatted = date_format.format(date);
1040     setProperty(propertyName, formatted);
1041     return formatted;
1042   }
1043
1044   /**
1045    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1046    * format) and returns as a Date, or null if parsing fails
1047    * 
1048    * @param propertyName
1049    * @return
1050    * 
1051    */
1052   public static Date getDateProperty(String propertyName)
1053   {
1054     String val = getProperty(propertyName);
1055     if (val != null)
1056     {
1057       try
1058       {
1059         return date_format.parse(val);
1060       } catch (Exception ex)
1061       {
1062         System.err.println("Invalid or corrupt date in property '"
1063                 + propertyName + "' : value was '" + val + "'");
1064       }
1065     }
1066     return null;
1067   }
1068
1069   /**
1070    * get and parse a property as an integer. send any parsing problems to
1071    * System.err
1072    * 
1073    * @param property
1074    * @return null or Integer
1075    */
1076   public static Integer getIntegerProperty(String property)
1077   {
1078     String val = getProperty(property);
1079     if (val != null && (val = val.trim()).length() > 0)
1080     {
1081       try
1082       {
1083         return Integer.valueOf(val);
1084       } catch (NumberFormatException x)
1085       {
1086         System.err.println("Invalid integer in property '" + property
1087                 + "' (value was '" + val + "')");
1088       }
1089     }
1090     return null;
1091   }
1092
1093   /**
1094    * Set the specified value, or remove it if null or empty. Does not save the
1095    * properties file.
1096    * 
1097    * @param propName
1098    * @param value
1099    */
1100   public static void setOrRemove(String propName, String value)
1101   {
1102     if (propName == null)
1103     {
1104       return;
1105     }
1106     if (value == null || value.trim().length() < 1)
1107     {
1108       getInstance().applicationProperties.remove(propName);
1109     }
1110     else
1111     {
1112       getInstance().applicationProperties.setProperty(propName, value);
1113     }
1114   }
1115
1116   /**
1117    * Loads in user colour schemes from files.
1118    * 
1119    * @param files
1120    *          a '|'-delimited list of file paths
1121    */
1122   public static void initUserColourSchemes(String files)
1123   {
1124     if (files == null || files.length() == 0)
1125     {
1126       return;
1127     }
1128
1129     // In case colours can't be loaded, we'll remove them
1130     // from the default list here.
1131     StringBuffer coloursFound = new StringBuffer();
1132     StringTokenizer st = new StringTokenizer(files, "|");
1133     while (st.hasMoreElements())
1134     {
1135       String file = st.nextToken();
1136       try
1137       {
1138         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1139         if (ucs != null)
1140         {
1141           if (coloursFound.length() > 0)
1142           {
1143             coloursFound.append("|");
1144           }
1145           coloursFound.append(file);
1146           ColourSchemes.getInstance().registerColourScheme(ucs);
1147         }
1148       } catch (Exception ex)
1149       {
1150         System.out.println("Error loading User ColourFile\n" + ex);
1151       }
1152     }
1153     if (!files.equals(coloursFound.toString()))
1154     {
1155       if (coloursFound.toString().length() > 1)
1156       {
1157         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1158                 coloursFound.toString());
1159       }
1160       else
1161       {
1162         getInstance().applicationProperties
1163                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1164       }
1165     }
1166   }
1167
1168   /**
1169    * Initial logging information helper for various versions output
1170    * 
1171    * @param prefix
1172    * @param value
1173    * @param defaultValue
1174    */
1175   private static void appendIfNotNull(StringBuilder sb, String prefix,
1176           String value, String suffix, String defaultValue)
1177   {
1178     if (value == null && defaultValue == null)
1179     {
1180       return;
1181     }
1182     String line = prefix + (value != null ? value : defaultValue) + suffix;
1183     sb.append(line);
1184   }
1185
1186   /**
1187    * 
1188    * @return Jalview version, build details and JVM platform version for console
1189    */
1190   public static String getVersionDetailsForConsole()
1191   {
1192     StringBuilder sb = new StringBuilder();
1193     sb.append("Jalview Version: "
1194             + jalview.bin.Cache.getDefault("VERSION", "TEST"));
1195     sb.append("\n");
1196     sb.append("Jalview Installation: "
1197             + jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1198     sb.append("\n");
1199     sb.append("Build Date: "
1200             + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1201     sb.append("\n");
1202     sb.append("Java version: " + System.getProperty("java.version"));
1203     sb.append("\n");
1204     sb.append(System.getProperty("os.arch") + " "
1205             + System.getProperty("os.name") + " "
1206             + System.getProperty("os.version"));
1207     sb.append("\n");
1208     appendIfNotNull(sb, "Install4j version: ",
1209             System.getProperty("sys.install4jVersion"), "\n", null);
1210     appendIfNotNull(sb, "Install4j template version: ",
1211             System.getProperty("installer_template_version"), "\n", null);
1212     appendIfNotNull(sb, "Launcher version: ",
1213             System.getProperty("launcher_version"), "\n", null);
1214     if (jalview.bin.Cache.getDefault("VERSION", "TEST")
1215             .equals("DEVELOPMENT"))
1216     {
1217       appendIfNotNull(sb, "Getdown appdir: ",
1218               System.getProperty("getdownappdir"), "\n", null);
1219       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1220               "\n", "unknown");
1221     }
1222     return sb.toString();
1223   }
1224
1225   /**
1226    * 
1227    * @return build details as reported in splashscreen
1228    */
1229   public static String getBuildDetailsForSplash()
1230   {
1231     // consider returning more human friendly info
1232     // eg 'built from Source' or update channel
1233     return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1234   }
1235
1236   /**
1237    * 
1238    * For AppletParams and Preferences ok_actionPerformed and
1239    * startupFileTextfield_mouseClicked
1240    * 
1241    * Sets a property value for the running application, without saving it to the
1242    * properties file
1243    * 
1244    * @param key
1245    * @param obj
1246    */
1247   public static void setPropertyNoSave(String key, String obj)
1248   {
1249     getInstance().setPropertyImpl(key, obj, false);
1250   }
1251
1252   /**
1253    * Sets a property value, and optionally also saves the current properties to
1254    * file
1255    * 
1256    * @param key
1257    * @param obj
1258    * @param andSave
1259    * @return
1260    */
1261   private Object setPropertyImpl(
1262           String key, String obj, boolean andSave)
1263   {
1264     Object oldValue = null;
1265     try
1266     {
1267       oldValue = applicationProperties.setProperty(key, obj);
1268       if (andSave && !propsAreReadOnly && propertiesFile != null)
1269       {
1270         FileOutputStream out = new FileOutputStream(propertiesFile);
1271         applicationProperties.store(out, "---JalviewX Properties File---");
1272         out.close();
1273       }
1274     } catch (Exception ex)
1275     {
1276       System.out.println(
1277               "Error setting property: " + key + " " + obj + "\n" + ex);
1278     }
1279     return oldValue;
1280   }
1281
1282 }