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