5688ae1eb06727bd13811434fa182c475068677a
[jalview.git] / src / jalview / bin / Cache.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, 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 java.io.*;
21 import java.util.*;
22
23 import org.apache.log4j.*;
24 import org.biojava.dasobert.dasregistry.Das1Source;
25
26 /**
27  * Stores and retrieves Jalview Application Properties Lists and fields within
28  * list entries are separated by '|' symbols unless otherwise stated (|) clauses
29  * are alternative values for a tag. <br>
30  * <br>
31  * Current properties include:
32  * <ul>
33  * <br>
34  * logs.Axis.Level - one of the stringified Levels for log4j controlling the
35  * logging level for axis (used for web services) <br>
36  * </li>
37  * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
38  * the logging level for castor (used for serialization) <br>
39  * </li>
40  * <li>logs.Jalview.Level - Cache.log stringified level. <br>
41  * </li>
42  * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
43  * startup</li>
44  * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.</li>
45  * <li>SCREEN_WIDTH</li>
46  * <li>SCREEN_HEIGHT</li>
47  * <li>SCREEN_Y=285</li>
48  * <li>SCREEN_X=371</li>
49  * <li>SHOW_FULLSCREEN boolean</li>
50  * <li>FONT_NAME java font name for alignment text display</li>
51  * <li>FONT_SIZE size of displayed alignment text</li>
52  * <li>FONT_STYLE style of font displayed (sequence labels are always italic)</li>
53  * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
54  * <li>LAST_DIRECTORY last directory for browsing alignment</li>
55  * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
56  * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
57  * <li>SHOW_IDENTITY show percentage identity annotation</li>
58  * <li>SHOW_QUALITY show alignment quality annotation</li>
59  * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
60  * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
61  * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
62  * annotation row</li>
63  * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
64  * <li>DEFAULT_FILE_FORMAT file format used to save</li>
65  * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
66  * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
67  * <li>VERSION the version of the jalview build</li>
68  * <li>BUILD_DATE date of this build</li>
69  * <li>LATEST_VERSION the latest jalview version advertised on the
70  * www.jalview.org</li>
71  * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
72  * descriptions</li>
73  * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
74  * suffix to file</li>
75  * <li>RECENT_URL list of recently retrieved URLs</li>
76  * <li>RECENT_FILE list of recently opened files</li>
77  * <li>USE_PROXY flag for whether a http proxy is to be used</li>
78  * <li>PROXY_SERVER the proxy</li>
79  * <li>PROXY_PORT</li>
80  * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
81  * service</li>
82  * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
83  * service</li>
84  * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
85  * collecting usage statistics</li>
86  * <li>DAS_LOCAL_SOURCE list of local das sources</li>
87  * <li>SHOW_OVERVIEW boolean for overview window display</li>
88  * <li>ANTI_ALIAS boolean for smooth fonts</li>
89  * <li>RIGHT_ALIGN_IDS boolean</li>
90  * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
91  * <li>PAD_GAPS boolean</li>
92  * <li>ID_ITALICS boolean</li>
93  * <li>SHOW_JV_SUFFIX</li>
94  * <li>WRAP_ALIGNMENT</li>
95  * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
96  * style check</li>
97  * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
98  * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
99  * $SEQUENCE_ID$</li>
100  * <li>GROUP_LINKS list of name|URL[|&lt;separator&gt;] tuples - see
101  * jalview.utils.GroupURLLink for more info</li>
102  * <li>DAS_REGISTRY_URL the registry to query</li>
103  * <li>DEFAULT_BROWSER for unix</li>
104  * <li>DAS_ACTIVE_SOURCE list of active sources</li>
105  * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
106  * (false)</li>
107  * <li>VERSION_CHECK (true) check for the latest release version from
108  * www.jalview.org</li>
109  * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
110  * ID tooltip</li>
111  * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
112  * ID tooltip</li>
113  * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
114  * displayed as '.'</li>
115  * <li>SORT_BY_TREE (false) sort the current alignment view according to the
116  * order of a newly displayed tree</li>
117  * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
118  * sequence ID strings before attempting retrieval from any datasource</li>
119  * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
120  * alignment.</li>
121  * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
122  * in the alignment.</li>
123  * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
124  * histogram.</li>
125  * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
126  * logo.</li>
127  * 
128  * <li></li>
129  * 
130  * <li></li>
131  * 
132  * </ul>
133  * 
134  * @author $author$
135  * @version $Revision$
136  */
137 public class Cache
138 {
139   /**
140    * property giving log4j level for CASTOR loggers
141    */
142   public static final String CASTORLOGLEVEL = "logs.Castor.level";
143
144   /**
145    * property giving log4j level for AXIS loggers
146    */
147   public static final String AXISLOGLEVEL = "logs.Axis.level";
148
149   /**
150    * property giving log4j level for Jalview Log
151    */
152   public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
153
154   public static final String DAS_LOCAL_SOURCE = "DAS_LOCAL_SOURCE";
155
156   public static final String DAS_REGISTRY_URL = "DAS_REGISTRY_URL";
157
158   public static final String DAS_ACTIVE_SOURCE = "DAS_ACTIVE_SOURCE";
159
160   /**
161    * Initialises the Jalview Application Log
162    */
163   public static Logger log;
164
165   /** Jalview Properties */
166   public static Properties applicationProperties = new Properties();
167
168   /** Default file is ~/.jalview_properties */
169   static String propertiesFile;
170
171   public static void initLogger()
172   {
173     if (log!=null)
174     {
175       return;
176     }
177     try
178     {
179       // TODO: redirect stdout and stderr here in order to grab the output of
180       // the log
181
182       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
183               "System.err");
184       ap.setName("JalviewLogger");
185       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
186       // log output
187       Logger laxis = Logger.getLogger("org.apache.axis");
188       Logger lcastor = Logger.getLogger("org.exolab.castor");
189       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
190
191       laxis.setLevel(Level.toLevel(Cache.getDefault("logs.Axis.Level",
192               Level.INFO.toString())));
193       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
194               Level.INFO.toString())));
195       lcastor = Logger.getLogger("org.exolab.castor.xml");
196       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
197               Level.INFO.toString())));
198       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
199       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
200       // Level.INFO.toString())));
201       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache.getDefault(
202               "logs.Jalview.level", Level.INFO.toString())));
203       // laxis.addAppender(ap);
204       // lcastor.addAppender(ap);
205       // jalview.bin.Cache.log.addAppender(ap);
206       // Tell the user that debug is enabled
207       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
208     } catch (Exception ex)
209     {
210       System.err.println("Problems initializing the log4j system\n");
211       ex.printStackTrace(System.err);
212     }
213   }
214
215   /** Called when Jalview is started */
216   public static void loadProperties(String propsFile)
217   {
218     propertiesFile = propsFile;
219     if (propsFile == null)
220     {
221       propertiesFile = System.getProperty("user.home") + File.separatorChar
222               + ".jalview_properties";
223     }
224
225     try
226     {
227       FileInputStream fis = new FileInputStream(propertiesFile);
228       applicationProperties.load(fis);
229       applicationProperties.remove("LATEST_VERSION");
230       applicationProperties.remove("VERSION");
231       fis.close();
232     } catch (Exception ex)
233     {
234       System.out.println("Error reading properties file: " + ex);
235     }
236
237     if (getDefault("USE_PROXY", false))
238     {
239       System.out.println("Using proxyServer: "
240               + getDefault("PROXY_SERVER", null) + " proxyPort: "
241               + getDefault("PROXY_PORT", null));
242       System
243               .setProperty("http.proxyHost", getDefault("PROXY_SERVER",
244                       null));
245       System.setProperty("http.proxyPort", getDefault("PROXY_PORT", null));
246     }
247
248     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
249     // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
250     // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
251     try
252     {
253       String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
254               .getCodeSource().getLocation().toString().concat(
255                       "!/.build_properties"));
256
257       java.net.URL localJarFileURL = new java.net.URL(buildDetails);
258
259       InputStream in = localJarFileURL.openStream();
260       applicationProperties.load(in);
261       in.close();
262     } catch (Exception ex)
263     {
264       System.out.println("Error reading build details: " + ex);
265       applicationProperties.remove("VERSION");
266     }
267
268     String jnlpVersion = System.getProperty("jalview.version");
269     String codeVersion = getProperty("VERSION");
270
271     if (codeVersion == null)
272     {
273       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
274       codeVersion = "Test";
275       jnlpVersion = "Test";
276     }
277
278     System.out.println("Jalview Version: " + codeVersion);
279
280     // jnlpVersion will be null if we're using InstallAnywhere
281     // Dont do this check if running in headless mode
282     if (jnlpVersion == null
283             && getDefault("VERSION_CHECK", true)
284             && (System.getProperty("java.awt.headless") == null || System
285                     .getProperty("java.awt.headless").equals("false")))
286     {
287
288       class VersionChecker extends Thread
289       {
290         public void run()
291         {
292           String orgtimeout = System
293                   .getProperty("sun.net.client.defaultConnectTimeout");
294           if (orgtimeout == null)
295           {
296             orgtimeout = "30";
297             System.out.println("# INFO: Setting default net timeout to "
298                     + orgtimeout + " seconds.");
299           }
300           String jnlpVersion = null;
301           try
302           {
303             System.setProperty("sun.net.client.defaultConnectTimeout",
304                     "5000");
305             java.net.URL url = new java.net.URL(
306                     "http://www.jalview.org/webstart/jalview.jnlp");
307             BufferedReader in = new BufferedReader(new InputStreamReader(
308                     url.openStream()));
309             String line = null;
310             while ((line = in.readLine()) != null)
311             {
312               if (line.indexOf("jalview.version") == -1)
313               {
314                 continue;
315               }
316
317               line = line.substring(line.indexOf("value=") + 7);
318               line = line.substring(0, line.lastIndexOf("\""));
319               jnlpVersion = line;
320               break;
321             }
322           } catch (Exception ex)
323           {
324             System.out
325                     .println("Non-fatal exceptions when checking version at www.jalview.org :");
326             System.out.println(ex);
327             jnlpVersion = getProperty("VERSION");
328           }
329           System.setProperty("sun.net.client.defaultConnectTimeout",
330                   orgtimeout);
331
332           setProperty("LATEST_VERSION", jnlpVersion);
333         }
334       }
335
336       VersionChecker vc = new VersionChecker();
337       vc.start();
338     }
339     else
340     {
341       if (jnlpVersion != null)
342       {
343         setProperty("LATEST_VERSION", jnlpVersion);
344       }
345       else
346       {
347         applicationProperties.remove("LATEST_VERSION");
348       }
349     }
350
351     setProperty("VERSION", codeVersion);
352
353     // LOAD USERDEFINED COLOURS
354     jalview.gui.UserDefinedColours
355             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
356     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
357             false);
358   }
359
360   /**
361    * Gets Jalview application property of given key. Returns null if key not
362    * found
363    * 
364    * @param key
365    *          Name of property
366    * 
367    * @return Property value
368    */
369   public static String getProperty(String key)
370   {
371     return applicationProperties.getProperty(key);
372   }
373
374   /**
375    * These methods are used when checking if the saved preference is different
376    * to the default setting
377    */
378
379   public static boolean getDefault(String property, boolean def)
380   {
381     String string = getProperty(property);
382     if (string != null)
383     {
384       def = Boolean.valueOf(string).booleanValue();
385     }
386
387     return def;
388   }
389
390   /**
391    * These methods are used when checking if the saved preference is different
392    * to the default setting
393    */
394   public static String getDefault(String property, String def)
395   {
396     String string = getProperty(property);
397     if (string != null)
398     {
399       return string;
400     }
401
402     return def;
403   }
404
405   /**
406    * Stores property in the file "HOME_DIR/.jalview_properties"
407    * 
408    * @param key
409    *          Name of object
410    * @param obj
411    *          String value of property
412    * 
413    * @return String value of property
414    */
415   public static String setProperty(String key, String obj)
416   {
417     try
418     {
419       FileOutputStream out = new FileOutputStream(propertiesFile);
420       applicationProperties.setProperty(key, obj);
421       applicationProperties.store(out, "---JalviewX Properties File---");
422       out.close();
423     } catch (Exception ex)
424     {
425       System.out.println("Error setting property: " + key + " " + obj
426               + "\n" + ex);
427     }
428     return obj;
429   }
430
431   /**
432    * remove the specified property from the jalview properties file
433    * 
434    * @param string
435    */
436   public static void removeProperty(String string)
437   {
438     applicationProperties.remove(string);
439     saveProperties();
440   }
441
442   /**
443    * save the properties to the jalview properties path
444    */
445   public static void saveProperties()
446   {
447     try
448     {
449       FileOutputStream out = new FileOutputStream(propertiesFile);
450       applicationProperties.store(out, "---JalviewX Properties File---");
451       out.close();
452     } catch (Exception ex)
453     {
454       System.out.println("Error saving properties: " + ex);
455     }
456   }
457
458   /**
459    * internal vamsas class discovery state
460    */
461   private static int vamsasJarsArePresent = -1;
462
463   /**
464    * Searches for vamsas client classes on class path.
465    * 
466    * @return true if vamsas client is present on classpath
467    */
468   public static boolean vamsasJarsPresent()
469   {
470     if (vamsasJarsArePresent == -1)
471     {
472       try
473       {
474         if (jalview.jbgui.GDesktop.class.getClassLoader().loadClass(
475                 "uk.ac.vamsas.client.VorbaId") != null)
476         {
477           jalview.bin.Cache.log
478                   .debug("Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
479           vamsasJarsArePresent = 1;
480           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
481           lvclient.setLevel(Level.toLevel(Cache.getDefault(
482                   "logs.Vamsas.Level", Level.INFO.toString())));
483
484           lvclient.addAppender(log.getAppender("JalviewLogger"));
485           // Tell the user that debug is enabled
486           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
487         }
488       } catch (Exception e)
489       {
490         vamsasJarsArePresent = 0;
491         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
492       }
493     }
494     return (vamsasJarsArePresent > 0);
495   }
496
497   /**
498    * internal vamsas class discovery state
499    */
500   private static int groovyJarsArePresent = -1;
501
502   /**
503    * Searches for vamsas client classes on class path.
504    * 
505    * @return true if vamsas client is present on classpath
506    */
507   public static boolean groovyJarsPresent()
508   {
509     if (groovyJarsArePresent == -1)
510     {
511       try
512       {
513         if (Cache.class.getClassLoader().loadClass(
514                 "groovy.lang.GroovyObject") != null)
515         {
516           jalview.bin.Cache.log
517                   .debug("Found Groovy (groovy.lang.GroovyObject can be loaded)");
518           groovyJarsArePresent = 1;
519           Logger lgclient = Logger.getLogger("groovy");
520           lgclient.setLevel(Level.toLevel(Cache.getDefault(
521                   "logs.Groovy.Level", Level.INFO.toString())));
522
523           lgclient.addAppender(log.getAppender("JalviewLogger"));
524           // Tell the user that debug is enabled
525           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
526         }
527       } catch (Error e)
528       {
529         groovyJarsArePresent = 0;
530         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
531       } catch (Exception e)
532       {
533         groovyJarsArePresent = 0;
534         jalview.bin.Cache.log.debug("Groovy Classes are not present");
535       }
536     }
537     return (groovyJarsArePresent > 0);
538   }
539
540   /**
541    * generate Das1Sources from the local das source list
542    * 
543    * @return Vector of Das1Sources
544    */
545   public static Vector getLocalDasSources()
546   {
547     Vector localSources = new Vector();
548     String local = jalview.bin.Cache.getProperty("DAS_LOCAL_SOURCE");
549     if (local != null)
550     {
551       StringTokenizer st = new StringTokenizer(local, "\t");
552       while (st.hasMoreTokens())
553       {
554         String token = st.nextToken();
555         int bar = token.indexOf("|");
556         Das1Source source = new Das1Source();
557         source.setUrl(token.substring(bar + 1));
558         if (source.getUrl().startsWith("sequence:"))
559         {
560           source.setUrl(source.getUrl().substring(9));
561           // this source also serves sequences as well as features
562           source.setCapabilities(new String[]
563           { "sequence", "features" });
564         }
565         else
566         {
567           // default is that all user added sources serve features
568           source.setCapabilities(new String[]
569           { "features" });
570         }
571
572         source.setNickname(token.substring(0, bar));
573
574         localSources.addElement(source);
575       }
576     }
577     return localSources;
578   }
579
580   /**
581    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
582    * enabled.
583    */
584   protected static Object tracker = null;
585
586   protected static Class trackerfocus = null;
587
588   protected static Class jgoogleanalyticstracker = null;
589
590   /**
591    * Initialise the google tracker if it is not done already.
592    */
593   public static void initGoogleTracker()
594   {
595     if (tracker == null)
596     {
597       if (jgoogleanalyticstracker == null)
598       {
599         // try to get the tracker class
600         try
601         {
602           jgoogleanalyticstracker = Cache.class
603                   .getClassLoader()
604                   .loadClass(
605                           "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
606           trackerfocus = Cache.class.getClassLoader().loadClass(
607                   "com.boxysystems.jgoogleanalytics.FocusPoint");
608         } catch (Exception e)
609         {
610           log
611                   .debug("com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
612           tracker = null;
613           jgoogleanalyticstracker = null;
614           trackerfocus = null;
615           return;
616         }
617       }
618       // now initialise tracker
619       Exception re = null, ex = null;
620       Error err = null;
621       String vrs = "No Version Accessible";
622       try
623       {
624         // Google analytics tracking code for Library Finder
625         tracker = jgoogleanalyticstracker.getConstructor(new Class[]
626         { String.class, String.class, String.class }).newInstance(
627                 new Object[]
628                 {
629                     "Jalview Desktop",
630                     (vrs = jalview.bin.Cache.getProperty("VERSION")
631                             + "_"
632                             + jalview.bin.Cache.getDefault("BUILD_DATE",
633                                     "unknown")), "UA-9060947-1" });
634         jgoogleanalyticstracker.getMethod("trackAsynchronously",
635                 new Class[]
636                 { trackerfocus }).invoke(tracker, new Object[]
637         { trackerfocus.getConstructor(new Class[]
638         { String.class }).newInstance(new Object[]
639         { "Application Started." }) });
640       } catch (RuntimeException e)
641       {
642         re = e;
643       } catch (Exception e)
644       {
645         ex = e;
646       } catch (Error e)
647       {
648         err = e;
649       }
650       if (re != null || ex != null || err != null)
651       {
652         if (log != null)
653         {
654           if (re != null)
655             log
656                     .debug(
657                             "Caught runtime exception in googletracker init:",
658                             re);
659           if (ex != null)
660             log.warn(
661                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
662                             + vrs, ex);
663           if (err != null)
664             log.error(
665                     "Whilst initing GoogleTracker for Jalview Desktop version "
666                             + vrs, err);
667         }
668         else
669         {
670           if (re != null)
671           {
672             System.err
673                     .println("Debug: Caught runtime exception in googletracker init:"
674                             + vrs);
675             re.printStackTrace();
676           }
677           if (ex != null)
678           {
679             System.err
680                     .println("Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
681                             + vrs);
682             ex.printStackTrace();
683           }
684
685           if (err != null)
686           {
687             System.err
688                     .println("ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
689                             + vrs);
690             err.printStackTrace();
691           }
692         }
693       }
694       else
695       {
696         log.debug("Successfully initialised tracker.");
697       }
698     }
699   }
700
701 }