JAL-1026 - insert a sensible default for proxy so Jalview doesn't crash out immediatl...
[jalview.git] / src / jalview / bin / Cache.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.bin;
19
20 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
21 import jalview.ws.dbsources.das.datamodel.DasSourceRegistry;
22
23 import java.awt.Color;
24 import java.io.*;
25 import java.text.DateFormat;
26 import java.text.SimpleDateFormat;
27 import java.util.*;
28
29 import org.apache.log4j.*;
30
31 /**
32  * Stores and retrieves Jalview Application Properties Lists and fields within
33  * list entries are separated by '|' symbols unless otherwise stated (|) clauses
34  * are alternative values for a tag. <br>
35  * <br>
36  * Current properties include:
37  * <ul>
38  * <br>
39  * logs.Axis.Level - one of the stringified Levels for log4j controlling the
40  * logging level for axis (used for web services) <br>
41  * </li>
42  * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
43  * the logging level for castor (used for serialization) <br>
44  * </li>
45  * <li>logs.Jalview.Level - Cache.log stringified level. <br>
46  * </li>
47  * <li>SCREEN_WIDTH</li>
48  * <li>SCREEN_HEIGHT</li>
49  * <li>SCREEN_Y=285</li>
50  * <li>SCREEN_X=371</li>
51  * <li>SHOW_FULLSCREEN boolean</li>
52  * <li>FONT_NAME java font name for alignment text display</li>
53  * <li>FONT_SIZE size of displayed alignment text</li>
54  * <li>FONT_STYLE style of font displayed (sequence labels are always italic)</li>
55  * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
56  * <li>LAST_DIRECTORY last directory for browsing alignment</li>
57  * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
58  * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
59  * <li>SHOW_IDENTITY show percentage identity annotation</li>
60  * <li>SHOW_QUALITY show alignment quality annotation</li>
61  * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
62  * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
63  * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
64  * annotation row</li>
65  * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
66  * <li>DEFAULT_FILE_FORMAT file format used to save</li>
67  * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
68  * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
69  * <li>VERSION the version of the jalview build</li>
70  * <li>BUILD_DATE date of this build</li>
71  * <li>LATEST_VERSION the latest jalview version advertised on the
72  * www.jalview.org</li>
73  * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
74  * descriptions</li>
75  * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
76  * suffix to file</li>
77  * <li>RECENT_URL list of recently retrieved URLs</li>
78  * <li>RECENT_FILE list of recently opened files</li>
79  * <li>USE_PROXY flag for whether a http proxy is to be used</li>
80  * <li>PROXY_SERVER the proxy</li>
81  * <li>PROXY_PORT</li>
82  * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
83  * service</li>
84  * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
85  * service</li>
86  * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
87  * collecting usage statistics</li>
88  * <li>DAS_LOCAL_SOURCE list of local das sources</li>
89  * <li>SHOW_OVERVIEW boolean for overview window display</li>
90  * <li>ANTI_ALIAS boolean for smooth fonts</li>
91  * <li>RIGHT_ALIGN_IDS boolean</li>
92  * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
93  * <li>PAD_GAPS boolean</li>
94  * <li>ID_ITALICS boolean</li>
95  * <li>SHOW_JV_SUFFIX</li>
96  * <li>WRAP_ALIGNMENT</li>
97  * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
98  * style check</li>
99  * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
100  * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
101  * $SEQUENCE_ID$</li>
102  * <li>GROUP_LINKS list of name|URL[|&lt;separator&gt;] tuples - see
103  * jalview.utils.GroupURLLink for more info</li>
104  * <li>DAS_REGISTRY_URL the registry to query</li>
105  * <li>DEFAULT_BROWSER for unix</li>
106  * <li>DAS_ACTIVE_SOURCE list of active sources</li>
107  * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
108  * (false)</li>
109  * <li>VERSION_CHECK (true) check for the latest release version from
110  * www.jalview.org (or the alias given by the www.jalview.org property)</li>
111  * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
112  * ID tooltip</li>
113  * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
114  * ID tooltip</li>
115  * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
116  * displayed as '.'</li>
117  * <li>SORT_BY_TREE (false) sort the current alignment view according to the
118  * order of a newly displayed tree</li>
119  * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
120  * sequence ID strings before attempting retrieval from any datasource</li>
121  * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
122  * alignment.</li>
123  * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
124  * in the alignment.</li>
125  * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
126  * histogram.</li>
127  * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
128  * logo.</li>
129  * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
130  * logo normalised to row height rather than histogram height.</li>
131  * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
132  * respond to selections made in other alignments containing the same sequences.
133  * </li>
134  * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
135  * warning dialog box is displayed.</li>
136  * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation when shading by annotation</li>
137  * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation when shading by annotation</li>
138  * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP requests to be redirected to a mirror of http://www.jalview.org</li>
139  * 
140  * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported alignment figure to accommodate even the longest sequence ID or annotation label.</li>
141  * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true will override this).</li>
142  * <li></li>
143  * 
144  * </ul>
145  * Deprecated settings:
146  * <ul>
147  *  * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
148  * startup (JWS1 services only)</li>
149  * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints. (JWS1 services only)</li>
150  * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2 services in the desktop GUI</li>
151  * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing panel in web service preferences</li> 
152  * </ul>
153  * @author $author$
154  * @version $Revision$
155  */
156 public class Cache
157 {
158   /**
159    * property giving log4j level for CASTOR loggers
160    */
161   public static final String CASTORLOGLEVEL = "logs.Castor.level";
162
163   /**
164    * property giving log4j level for AXIS loggers
165    */
166   public static final String AXISLOGLEVEL = "logs.Axis.level";
167
168   /**
169    * property giving log4j level for Jalview Log
170    */
171   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
172
173   public static final String DAS_LOCAL_SOURCE = "DAS_LOCAL_SOURCE";
174
175   public static final String DAS_REGISTRY_URL = "DAS_REGISTRY_URL";
176
177   public static final String DAS_ACTIVE_SOURCE = "DAS_ACTIVE_SOURCE";
178
179   /**
180    * Initialises the Jalview Application Log
181    */
182   public static Logger log;
183
184   /** Jalview Properties */
185   public static Properties applicationProperties = new Properties();
186
187   /** Default file is ~/.jalview_properties */
188   static String propertiesFile;
189
190   private static boolean propsAreReadOnly=false;
191
192   public static void initLogger()
193   {
194     if (log != null)
195     {
196       return;
197     }
198     try
199     {
200       // TODO: redirect stdout and stderr here in order to grab the output of
201       // the log
202
203       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
204               "System.err");
205       ap.setName("JalviewLogger");
206       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
207       // log output
208       Logger laxis = Logger.getLogger("org.apache.axis");
209       Logger lcastor = Logger.getLogger("org.exolab.castor");
210       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
211
212       laxis.setLevel(Level.toLevel(Cache.getDefault("logs.Axis.Level",
213               Level.INFO.toString())));
214       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
215               Level.INFO.toString())));
216       lcastor = Logger.getLogger("org.exolab.castor.xml");
217       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
218               Level.INFO.toString())));
219       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
220       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
221       // Level.INFO.toString())));
222       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache.getDefault(
223               "logs.Jalview.level", Level.INFO.toString())));
224       // laxis.addAppender(ap);
225       // lcastor.addAppender(ap);
226       // jalview.bin.Cache.log.addAppender(ap);
227       // Tell the user that debug is enabled
228       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
229     } catch (Exception ex)
230     {
231       System.err.println("Problems initializing the log4j system\n");
232       ex.printStackTrace(System.err);
233     }
234   }
235
236   /** Called when Jalview is started */
237   public static void loadProperties(String propsFile)
238   {
239     propertiesFile = propsFile;
240     if (propsFile == null)
241     {
242       propertiesFile = System.getProperty("user.home") + File.separatorChar
243               + ".jalview_properties";
244     } else {
245       // don't corrupt the file we've been given.
246       propsAreReadOnly = true;
247     }
248
249     try
250     {
251       InputStream fis;
252       try
253       {
254         fis = new java.net.URL(propertiesFile).openStream();
255         System.out.println("Loading jalview properties from : "
256                 + propertiesFile);
257         System.out
258                 .println("Disabling Jalview writing to user's local properties file.");
259         propsAreReadOnly = true;
260
261       } catch (Exception ex)
262       {
263         fis = null;
264       }
265       if (fis == null)
266       {
267         fis = new FileInputStream(propertiesFile);
268       }
269       applicationProperties.load(fis);
270       applicationProperties.remove("LATEST_VERSION");
271       applicationProperties.remove("VERSION");
272       fis.close();
273     } catch (Exception ex)
274     {
275       System.out.println("Error reading properties file: " + ex);
276     }
277
278     if (getDefault("USE_PROXY", false))
279     {
280       String proxyServer=getDefault("PROXY_SERVER", ""), proxyPort=getDefault("PROXY_PORT", "8080");
281       
282       System.out.println("Using proxyServer: "
283               + proxyServer + " proxyPort: "
284               + proxyPort );
285       
286       System.setProperty("http.proxyHost", proxyServer);
287       System.setProperty("http.proxyPort", proxyPort);
288     }
289
290     // LOAD THE AUTHORS FROM THE authors.props file
291     try
292     {
293       String authorDetails = "jar:".concat(Cache.class.getProtectionDomain()
294               .getCodeSource().getLocation().toString()
295               .concat("!/authors.props"));
296
297       java.net.URL localJarFileURL = new java.net.URL(authorDetails);
298
299       InputStream in = localJarFileURL.openStream();
300       applicationProperties.load(in);
301       in.close();
302     } catch (Exception ex)
303     {
304       System.out.println("Error reading author details: " + ex);
305       applicationProperties.remove("AUTHORS");
306       applicationProperties.remove("AUTHORFNAMES");
307       applicationProperties.remove("YEAR");
308     }
309
310     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
311     // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
312     // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
313     try
314     {
315       String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
316               .getCodeSource().getLocation().toString()
317               .concat("!/.build_properties"));
318
319       java.net.URL localJarFileURL = new java.net.URL(buildDetails);
320
321       InputStream in = localJarFileURL.openStream();
322       applicationProperties.load(in);
323       in.close();
324     } catch (Exception ex)
325     {
326       System.out.println("Error reading build details: " + ex);
327       applicationProperties.remove("VERSION");
328     }
329
330     String jnlpVersion = System.getProperty("jalview.version");
331     String codeVersion = getProperty("VERSION");
332
333     if (codeVersion == null)
334     {
335       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
336       codeVersion = "Test";
337       jnlpVersion = "Test";
338     }
339
340     System.out.println("Jalview Version: " + codeVersion);
341
342     // jnlpVersion will be null if we're using InstallAnywhere
343     // Dont do this check if running in headless mode
344     if (jnlpVersion == null
345             && getDefault("VERSION_CHECK", true)
346             && (System.getProperty("java.awt.headless") == null || System
347                     .getProperty("java.awt.headless").equals("false")))
348     {
349
350       class VersionChecker extends Thread
351       {
352         public void run()
353         {
354           String orgtimeout = System
355                   .getProperty("sun.net.client.defaultConnectTimeout");
356           if (orgtimeout == null)
357           {
358             orgtimeout = "30";
359             System.out.println("# INFO: Setting default net timeout to "
360                     + orgtimeout + " seconds.");
361           }
362           String jnlpVersion = null;
363           try
364           {
365             System.setProperty("sun.net.client.defaultConnectTimeout",
366                     "5000");
367             java.net.URL url = new java.net.URL(
368                     Cache.getDefault("www.jalview.org", "http://www.jalview.org")+"/webstart/jalview.jnlp");
369             BufferedReader in = new BufferedReader(new InputStreamReader(
370                     url.openStream()));
371             String line = null;
372             while ((line = in.readLine()) != null)
373             {
374               if (line.indexOf("jalview.version") == -1)
375               {
376                 continue;
377               }
378
379               line = line.substring(line.indexOf("value=") + 7);
380               line = line.substring(0, line.lastIndexOf("\""));
381               jnlpVersion = line;
382               break;
383             }
384           } catch (Exception ex)
385           {
386             System.out
387                     .println("Non-fatal exceptions when checking version at www.jalview.org :");
388             System.out.println(ex);
389             jnlpVersion = getProperty("VERSION");
390           }
391           System.setProperty("sun.net.client.defaultConnectTimeout",
392                   orgtimeout);
393
394           setProperty("LATEST_VERSION", jnlpVersion);
395         }
396       }
397
398       VersionChecker vc = new VersionChecker();
399       vc.start();
400     }
401     else
402     {
403       if (jnlpVersion != null)
404       {
405         setProperty("LATEST_VERSION", jnlpVersion);
406       }
407       else
408       {
409         applicationProperties.remove("LATEST_VERSION");
410       }
411     }
412
413     setProperty("VERSION", codeVersion);
414
415     // LOAD USERDEFINED COLOURS
416     jalview.gui.UserDefinedColours
417             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
418     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
419             false);
420   }
421
422   /**
423    * Gets Jalview application property of given key. Returns null if key not
424    * found
425    * 
426    * @param key
427    *          Name of property
428    * 
429    * @return Property value
430    */
431   public static String getProperty(String key)
432   {
433     return applicationProperties.getProperty(key);
434   }
435
436   /**
437    * These methods are used when checking if the saved preference is different
438    * to the default setting
439    */
440
441   public static boolean getDefault(String property, boolean def)
442   {
443     String string = getProperty(property);
444     if (string != null)
445     {
446       def = Boolean.valueOf(string).booleanValue();
447     }
448
449     return def;
450   }
451
452   /**
453    * These methods are used when checking if the saved preference is different
454    * to the default setting
455    */
456   public static String getDefault(String property, String def)
457   {
458     String string = getProperty(property);
459     if (string != null)
460     {
461       return string;
462     }
463
464     return def;
465   }
466
467   /**
468    * Stores property in the file "HOME_DIR/.jalview_properties"
469    * 
470    * @param key
471    *          Name of object
472    * @param obj
473    *          String value of property
474    * 
475    * @return String value of property
476    */
477   public static String setProperty(String key, String obj)
478   {
479
480     try
481     {
482       applicationProperties.setProperty(key, obj);
483       if (!propsAreReadOnly)
484       {
485         FileOutputStream out = new FileOutputStream(propertiesFile);
486         applicationProperties.store(out, "---JalviewX Properties File---");
487         out.close();
488       }
489     } catch (Exception ex)
490     {
491       System.out.println("Error setting property: " + key + " " + obj
492               + "\n" + ex);
493     }
494     return obj;
495   }
496
497   /**
498    * remove the specified property from the jalview properties file
499    * 
500    * @param string
501    */
502   public static void removeProperty(String string)
503   {
504     applicationProperties.remove(string);
505     saveProperties();
506   }
507
508   /**
509    * save the properties to the jalview properties path
510    */
511   public static void saveProperties()
512   {
513     if (!propsAreReadOnly)
514     {
515       try
516       {
517         FileOutputStream out = new FileOutputStream(propertiesFile);
518         applicationProperties.store(out, "---JalviewX Properties File---");
519         out.close();
520       } catch (Exception ex)
521       {
522         System.out.println("Error saving properties: " + ex);
523       }
524     }
525   }
526
527   /**
528    * internal vamsas class discovery state
529    */
530   private static int vamsasJarsArePresent = -1;
531
532   /**
533    * Searches for vamsas client classes on class path.
534    * 
535    * @return true if vamsas client is present on classpath
536    */
537   public static boolean vamsasJarsPresent()
538   {
539     if (vamsasJarsArePresent == -1)
540     {
541       try
542       {
543         if (jalview.jbgui.GDesktop.class.getClassLoader().loadClass(
544                 "uk.ac.vamsas.client.VorbaId") != null)
545         {
546           jalview.bin.Cache.log
547                   .debug("Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
548           vamsasJarsArePresent = 1;
549           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
550           lvclient.setLevel(Level.toLevel(Cache.getDefault(
551                   "logs.Vamsas.Level", Level.INFO.toString())));
552
553           lvclient.addAppender(log.getAppender("JalviewLogger"));
554           // Tell the user that debug is enabled
555           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
556         }
557       } catch (Exception e)
558       {
559         vamsasJarsArePresent = 0;
560         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
561       }
562     }
563     return (vamsasJarsArePresent > 0);
564   }
565
566   /**
567    * internal vamsas class discovery state
568    */
569   private static int groovyJarsArePresent = -1;
570
571   /**
572    * Searches for vamsas client classes on class path.
573    * 
574    * @return true if vamsas client is present on classpath
575    */
576   public static boolean groovyJarsPresent()
577   {
578     if (groovyJarsArePresent == -1)
579     {
580       try
581       {
582         if (Cache.class.getClassLoader().loadClass(
583                 "groovy.lang.GroovyObject") != null)
584         {
585           jalview.bin.Cache.log
586                   .debug("Found Groovy (groovy.lang.GroovyObject can be loaded)");
587           groovyJarsArePresent = 1;
588           Logger lgclient = Logger.getLogger("groovy");
589           lgclient.setLevel(Level.toLevel(Cache.getDefault(
590                   "logs.Groovy.Level", Level.INFO.toString())));
591
592           lgclient.addAppender(log.getAppender("JalviewLogger"));
593           // Tell the user that debug is enabled
594           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
595         }
596       } catch (Error e)
597       {
598         groovyJarsArePresent = 0;
599         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
600       } catch (Exception e)
601       {
602         groovyJarsArePresent = 0;
603         jalview.bin.Cache.log.debug("Groovy Classes are not present");
604       }
605     }
606     return (groovyJarsArePresent > 0);
607   }
608
609   /**
610    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
611    * enabled.
612    */
613   protected static Object tracker = null;
614
615   protected static Class trackerfocus = null;
616
617   protected static Class jgoogleanalyticstracker = null;
618
619   /**
620    * Initialise the google tracker if it is not done already.
621    */
622   public static void initGoogleTracker()
623   {
624     if (tracker == null)
625     {
626       if (jgoogleanalyticstracker == null)
627       {
628         // try to get the tracker class
629         try
630         {
631           jgoogleanalyticstracker = Cache.class
632                   .getClassLoader()
633                   .loadClass(
634                           "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
635           trackerfocus = Cache.class.getClassLoader().loadClass(
636                   "com.boxysystems.jgoogleanalytics.FocusPoint");
637         } catch (Exception e)
638         {
639           log.debug("com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
640           tracker = null;
641           jgoogleanalyticstracker = null;
642           trackerfocus = null;
643           return;
644         }
645       }
646       // now initialise tracker
647       Exception re = null, ex = null;
648       Error err = null;
649       String vrs = "No Version Accessible";
650       try
651       {
652         // Google analytics tracking code for Library Finder
653         tracker = jgoogleanalyticstracker.getConstructor(new Class[]
654         { String.class, String.class, String.class }).newInstance(
655                 new Object[]
656                 {
657                     "Jalview Desktop",
658                     (vrs = jalview.bin.Cache.getProperty("VERSION")
659                             + "_"
660                             + jalview.bin.Cache.getDefault("BUILD_DATE",
661                                     "unknown")), "UA-9060947-1" });
662         jgoogleanalyticstracker.getMethod("trackAsynchronously",
663                 new Class[]
664                 { trackerfocus }).invoke(tracker, new Object[]
665         { trackerfocus.getConstructor(new Class[]
666         { String.class }).newInstance(new Object[]
667         { "Application Started." }) });
668       } catch (RuntimeException e)
669       {
670         re = e;
671       } catch (Exception e)
672       {
673         ex = e;
674       } catch (Error e)
675       {
676         err = e;
677       }
678       if (re != null || ex != null || err != null)
679       {
680         if (log != null)
681         {
682           if (re != null)
683             log.debug("Caught runtime exception in googletracker init:", re);
684           if (ex != null)
685             log.warn(
686                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
687                             + vrs, ex);
688           if (err != null)
689             log.error(
690                     "Whilst initing GoogleTracker for Jalview Desktop version "
691                             + vrs, err);
692         }
693         else
694         {
695           if (re != null)
696           {
697             System.err
698                     .println("Debug: Caught runtime exception in googletracker init:"
699                             + vrs);
700             re.printStackTrace();
701           }
702           if (ex != null)
703           {
704             System.err
705                     .println("Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
706                             + vrs);
707             ex.printStackTrace();
708           }
709
710           if (err != null)
711           {
712             System.err
713                     .println("ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
714                             + vrs);
715             err.printStackTrace();
716           }
717         }
718       }
719       else
720       {
721         log.debug("Successfully initialised tracker.");
722       }
723     }
724   }
725
726   /**
727    * get the user's default colour if available
728    * @param property
729    * @param defcolour
730    * @return
731    */
732   public static Color getDefaultColour(String property, Color defcolour)
733   {
734     String colprop = getProperty(property);
735     if (colprop==null) {
736       return defcolour;
737     }
738     Color col = jalview.schemes.ColourSchemeProperty.getAWTColorFromName(colprop);
739     if (col==null)
740     {
741       try {
742         col = new jalview.schemes.UserColourScheme(colprop).findColour('A');
743       } catch (Exception ex)
744       {
745         log.warn("Couldn't parse '"+colprop+"' as a colour for "+property);
746         col=null;
747       }
748     }
749     return (col==null) ? defcolour: col;
750   }
751
752   /**
753    * store a colour as a Jalview user default property
754    * @param property
755    * @param colour     
756    */
757   public static void setColourProperty(String property, Color colour)
758   {
759     setProperty(property, jalview.util.Format
760           .getHexString(colour));
761   }
762
763   public static final DateFormat  date_format = SimpleDateFormat.getDateTimeInstance();
764
765   /**
766    * store a date in a jalview property
767    * @param string
768    * @param time
769    */
770   public static void setDateProperty(String property, Date time)
771   {
772     setProperty(property, date_format.format(time));
773   }
774   /**
775    * read a date stored in a jalview property
776    * @param property
777    * @return valid date as stored by setDateProperty, or null
778    * 
779    */
780   public static Date getDateProperty(String property)
781   {
782     String val = getProperty(property);
783     if (val!=null)
784     {
785       try {
786         return date_format.parse(val);
787       } catch (Exception ex)
788       {
789         System.err.println("Invalid or corrupt date in property '"+property+"' : value was '"+val+"'");
790       }
791     }
792     return null;
793   }
794
795   /**
796    * get and parse a property as an integer. send any parsing problems to System.err
797    * @param property
798    * @return null or Integer
799    */
800   public static Integer getIntegerProperty(String property)
801   {
802     String val=getProperty(property);
803     if (val!=null && (val=val.trim()).length()>0)
804     {
805       try {
806         return Integer.valueOf(val);
807       } catch (NumberFormatException x)
808       {
809         System.err.println("Invalid integer in property '"+property+"' (value was '"+val+"')");
810       }
811     }
812     return null;
813   }
814
815   private static DasSourceRegistryI sourceRegistry=null;
816   /**
817    * initialise and ..
818    * @return instance of the das source registry
819    */
820   public static DasSourceRegistryI getDasSourceRegistry()
821   {
822     if (sourceRegistry==null)
823     {
824       sourceRegistry = new DasSourceRegistry();
825     }
826     return sourceRegistry;
827   }
828 }