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