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