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