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