Merge remote-tracking branch 'origin/tasks/JAL-3035_remove_dasobert_dependency' into...
[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>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
89  * LABEL_AND_SEQUENCE</li>
90  * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
91  * sequence annotations</li>
92  * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
93  * annotation row</li>
94  * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
95  * <li>DEFAULT_FILE_FORMAT file format used to save</li>
96  * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
97  * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
98  * <li>VERSION the version of the jalview build</li>
99  * <li>BUILD_DATE date of this build</li>
100  * <li>LATEST_VERSION the latest jalview version advertised on the
101  * www.jalview.org</li>
102  * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
103  * descriptions</li>
104  * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
105  * suffix to file</li>
106  * <li>RECENT_URL list of recently retrieved URLs</li>
107  * <li>RECENT_FILE list of recently opened files</li>
108  * <li>USE_PROXY flag for whether a http proxy is to be used</li>
109  * <li>PROXY_SERVER the proxy</li>
110  * <li>PROXY_PORT</li>
111  * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
112  * service</li>
113  * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
114  * service</li>
115  * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
116  * collecting usage statistics</li>
117  * <li>SHOW_OVERVIEW boolean for overview window display</li>
118  * <li>ANTI_ALIAS boolean for smooth fonts</li>
119  * <li>RIGHT_ALIGN_IDS boolean</li>
120  * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
121  * <li>PAD_GAPS boolean</li>
122  * <li>ID_ITALICS boolean</li>
123  * <li>SHOW_JV_SUFFIX</li>
124  * <li>WRAP_ALIGNMENT</li>
125  * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
126  * style check</li>
127  * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
128  * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
129  * $SEQUENCE_ID$</li>
130  * <li>STORED_LINKS list of name|url pairs which user has entered but are not
131  * currently used
132  * <li>DEFAULT_LINK name of single url to be used when user double clicks a
133  * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
134  * <li>GROUP_LINKS list of name|URL[|&lt;separator&gt;] tuples - see
135  * jalview.utils.GroupURLLink for more info</li>
136  * <li>DEFAULT_BROWSER for unix</li>
137  * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
138  * (false)</li>
139  * <li>VERSION_CHECK (true) check for the latest release version from
140  * www.jalview.org (or the alias given by the www.jalview.org property)</li>
141  * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
142  * ID tooltip</li>
143  * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
144  * ID tooltip</li>
145  * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
146  * displayed as '.'</li>
147  * <li>SORT_BY_TREE (false) sort the current alignment view according to the
148  * order of a newly displayed tree</li>
149  * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
150  * sequence ID strings before attempting retrieval from any datasource</li>
151  * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
152  * alignment.</li>
153  * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
154  * in the alignment.</li>
155  * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
156  * histogram.</li>
157  * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
158  * logo.</li>
159  * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
160  * logo normalised to row height rather than histogram height.</li>
161  * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
162  * respond to selections made in other alignments containing the same sequences.
163  * </li>
164  * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
165  * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
166  * warning dialog box is displayed.</li>
167  * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
168  * when shading by annotation</li>
169  * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
170  * when shading by annotation</li>
171  * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
172  * requests to be redirected to a mirror of http://www.jalview.org</li>
173  * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
174  * alignment figure to accommodate even the longest sequence ID or annotation
175  * label.</li>
176  * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
177  * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
178  * will override this).</li>
179  * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
180  * record</li>
181  * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
182  * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
183  * display</li>
184  * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
185  * display</li>
186  * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
187  * display</li>
188  * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
189  * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
190  * </li>
191  * 
192  * </ul>
193  * Deprecated settings:
194  * <ul>
195  * *
196  * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
197  * startup (JWS1 services only)</li>
198  * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
199  * (JWS1 services only)</li>
200  * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
201  * services in the desktop GUI</li>
202  * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
203  * panel in web service preferences</li>
204  * </ul>
205  * 
206  * @author $author$
207  * @version $Revision$
208  */
209 public class Cache
210 {
211   /**
212    * property giving log4j level for CASTOR loggers
213    */
214   public static final String CASTORLOGLEVEL = "logs.Castor.level";
215
216   /**
217    * property giving log4j level for AXIS loggers
218    */
219   public static final String AXISLOGLEVEL = "logs.Axis.level";
220
221   /**
222    * property giving log4j level for Jalview Log
223    */
224   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
225
226   /**
227    * Sifts settings
228    */
229   public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
230           .getProperty("user.home") + File.separatorChar
231           + ".sifts_downloads" + File.separatorChar;
232
233   private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
234
235   private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
236
237   /**
238    * Identifiers.org download settings
239    */
240   private static final String ID_ORG_FILE = System.getProperty("user.home")
241           + File.separatorChar + ".identifiers.org.ids.json";
242
243   /**
244    * Allowed values are PDB or mmCIF
245    */
246   private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
247           .toString();
248
249   private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
250           .toString();
251
252   /*
253    * a date formatter using a fixed (rather than the user's) locale; 
254    * this ensures that date properties can be written and re-read successfully
255    * even if the user changes their locale setting
256    */
257   private static final DateFormat date_format = SimpleDateFormat
258           .getDateTimeInstance(SimpleDateFormat.MEDIUM,
259                   SimpleDateFormat.MEDIUM, Locale.UK);
260
261   /**
262    * Initialises the Jalview Application Log
263    */
264   public static Logger log;
265
266   /** Jalview Properties */
267   public static Properties applicationProperties = new Properties()
268   {
269     // override results in properties output in alphabetical order
270     @Override
271     public synchronized Enumeration<Object> keys()
272     {
273       return Collections.enumeration(new TreeSet<>(super.keySet()));
274     }
275   };
276
277   /** Default file is ~/.jalview_properties */
278   static String propertiesFile;
279
280   private static boolean propsAreReadOnly = false;
281
282   public static void initLogger()
283   {
284     if (log != null)
285     {
286       return;
287     }
288     try
289     {
290       // TODO: redirect stdout and stderr here in order to grab the output of
291       // the log
292
293       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
294               "System.err");
295       ap.setName("JalviewLogger");
296       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
297       // log output
298       Logger laxis = Logger.getLogger("org.apache.axis");
299       Logger lcastor = Logger.getLogger("org.exolab.castor");
300       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
301
302       laxis.setLevel(Level.toLevel(
303               Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
304       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
305               Level.INFO.toString())));
306       lcastor = Logger.getLogger("org.exolab.castor.xml");
307       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
308               Level.INFO.toString())));
309       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
310       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
311       // Level.INFO.toString())));
312       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
313               .getDefault("logs.Jalview.level", Level.INFO.toString())));
314       // laxis.addAppender(ap);
315       // lcastor.addAppender(ap);
316       // jalview.bin.Cache.log.addAppender(ap);
317       // Tell the user that debug is enabled
318       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
319     } catch (Exception ex)
320     {
321       System.err.println("Problems initializing the log4j system\n");
322       ex.printStackTrace(System.err);
323     }
324   }
325
326   /**
327    * Loads properties from the given properties file. Any existing properties
328    * are first cleared.
329    */
330   public static void loadProperties(String propsFile)
331   {
332     propertiesFile = propsFile;
333     if (propsFile == null)
334     {
335       propertiesFile = System.getProperty("user.home") + File.separatorChar
336               + ".jalview_properties";
337     }
338     else
339     {
340       // don't corrupt the file we've been given.
341       propsAreReadOnly = true;
342     }
343
344     try
345     {
346       InputStream fis;
347       try
348       {
349         fis = new java.net.URL(propertiesFile).openStream();
350         System.out.println(
351                 "Loading jalview properties from : " + propertiesFile);
352         System.out.println(
353                 "Disabling Jalview writing to user's local properties file.");
354         propsAreReadOnly = true;
355
356       } catch (Exception ex)
357       {
358         fis = null;
359       }
360       if (fis == null)
361       {
362         fis = new FileInputStream(propertiesFile);
363       }
364       applicationProperties.clear();
365       applicationProperties.load(fis);
366
367       // remove any old build properties
368
369       deleteBuildProperties();
370       fis.close();
371     } catch (Exception ex)
372     {
373       System.out.println("Error reading properties file: " + ex);
374     }
375
376     if (getDefault("USE_PROXY", false))
377     {
378       String proxyServer = getDefault("PROXY_SERVER", ""),
379               proxyPort = getDefault("PROXY_PORT", "8080");
380
381       System.out.println("Using proxyServer: " + proxyServer
382               + " proxyPort: " + proxyPort);
383
384       System.setProperty("http.proxyHost", proxyServer);
385       System.setProperty("http.proxyPort", proxyPort);
386     }
387
388     // LOAD THE AUTHORS FROM THE authors.props file
389     try
390     {
391       String authorDetails = "jar:"
392               .concat(Cache.class.getProtectionDomain().getCodeSource()
393                       .getLocation().toString().concat("!/authors.props"));
394
395       java.net.URL localJarFileURL = new java.net.URL(authorDetails);
396
397       InputStream in = localJarFileURL.openStream();
398       applicationProperties.load(in);
399       in.close();
400     } catch (Exception ex)
401     {
402       System.out.println("Error reading author details: " + ex);
403       applicationProperties.remove("AUTHORS");
404       applicationProperties.remove("AUTHORFNAMES");
405       applicationProperties.remove("YEAR");
406     }
407
408     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
409     // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
410     // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
411     try
412     {
413       String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
414               .getCodeSource().getLocation().toString()
415               .concat("!/.build_properties"));
416
417       java.net.URL localJarFileURL = new java.net.URL(buildDetails);
418
419       InputStream in = localJarFileURL.openStream();
420       applicationProperties.load(in);
421       in.close();
422     } catch (Exception ex)
423     {
424       System.out.println("Error reading build details: " + ex);
425       applicationProperties.remove("VERSION");
426     }
427
428     String jnlpVersion = System.getProperty("jalview.version");
429     String codeVersion = getProperty("VERSION");
430     String codeInstallation = getProperty("INSTALLATION");
431     if (codeVersion == null)
432     {
433       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
434       codeVersion = "Test";
435       jnlpVersion = "Test";
436       codeInstallation = "";
437     }
438     else
439     {
440       codeInstallation = " (" + codeInstallation + ")";
441     }
442     new BuildDetails(codeVersion, null, codeInstallation);
443
444     SiftsSettings
445             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
446
447     SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
448             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
449
450     SiftsSettings.setFailSafePIDThreshold(
451             jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
452                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
453
454     SiftsSettings.setCacheThresholdInDays(
455             jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
456                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
457
458     IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
459             "http://www.jalview.org/services/identifiers"));
460     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
461
462     System.out
463             .println("Jalview Version: " + codeVersion + codeInstallation);
464
465     StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
466             .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
467     StructureImportSettings
468             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
469     // StructureImportSettings
470     // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
471     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
472     // jnlpVersion will be null if we're using InstallAnywhere
473     // Dont do this check if running in headless mode
474     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
475             && (System.getProperty("java.awt.headless") == null || System
476                     .getProperty("java.awt.headless").equals("false")))
477     {
478
479       class VersionChecker extends Thread
480       {
481         @Override
482         public void run()
483         {
484           String orgtimeout = System
485                   .getProperty("sun.net.client.defaultConnectTimeout");
486           if (orgtimeout == null)
487           {
488             orgtimeout = "30";
489             System.out.println("# INFO: Setting default net timeout to "
490                     + orgtimeout + " seconds.");
491           }
492           String remoteVersion = null;
493           try
494           {
495             System.setProperty("sun.net.client.defaultConnectTimeout",
496                     "5000");
497             java.net.URL url = new java.net.URL(Cache
498                     .getDefault("www.jalview.org", "http://www.jalview.org")
499                     + "/webstart/jalview.jnlp");
500             BufferedReader in = new BufferedReader(
501                     new InputStreamReader(url.openStream()));
502             String line = null;
503             while ((line = in.readLine()) != null)
504             {
505               if (line.indexOf("jalview.version") == -1)
506               {
507                 continue;
508               }
509
510               line = line.substring(line.indexOf("value=") + 7);
511               line = line.substring(0, line.lastIndexOf("\""));
512               remoteVersion = line;
513               break;
514             }
515           } catch (Exception ex)
516           {
517             System.out.println(
518                     "Non-fatal exception when checking version at www.jalview.org :");
519             System.out.println(ex);
520             remoteVersion = getProperty("VERSION");
521           }
522           System.setProperty("sun.net.client.defaultConnectTimeout",
523                   orgtimeout);
524
525           setProperty("LATEST_VERSION", remoteVersion);
526         }
527       }
528
529       VersionChecker vc = new VersionChecker();
530       vc.start();
531     }
532     else
533     {
534       if (jnlpVersion != null)
535       {
536         setProperty("LATEST_VERSION", jnlpVersion);
537       }
538       else
539       {
540         applicationProperties.remove("LATEST_VERSION");
541       }
542     }
543
544     setProperty("VERSION", codeVersion);
545
546     // LOAD USERDEFINED COLOURS
547     jalview.bin.Cache
548             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
549     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
550             false);
551   }
552
553   private static void deleteBuildProperties()
554   {
555     applicationProperties.remove("LATEST_VERSION");
556     applicationProperties.remove("VERSION");
557     applicationProperties.remove("AUTHORS");
558     applicationProperties.remove("AUTHORFNAMES");
559     applicationProperties.remove("YEAR");
560     applicationProperties.remove("BUILD_DATE");
561     applicationProperties.remove("INSTALLATION");
562   }
563
564   /**
565    * Gets Jalview application property of given key. Returns null if key not
566    * found
567    * 
568    * @param key
569    *          Name of property
570    * 
571    * @return Property value
572    */
573   public static String getProperty(String key)
574   {
575     return applicationProperties.getProperty(key);
576   }
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 }