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