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