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