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