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