cebb50414d00c84864a3e39439865d0010bc716e
[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     try
174     {
175       // TODO: redirect stdout and stderr here in order to grab the output of
176       // the log
177
178       ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
179               "System.err");
180       ap.setName("JalviewLogger");
181       org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
182       // log output
183       Logger laxis = Logger.getLogger("org.apache.axis");
184       Logger lcastor = Logger.getLogger("org.exolab.castor");
185       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
186
187       laxis.setLevel(Level.toLevel(Cache.getDefault("logs.Axis.Level",
188               Level.INFO.toString())));
189       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
190               Level.INFO.toString())));
191       lcastor = Logger.getLogger("org.exolab.castor.xml");
192       lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
193               Level.INFO.toString())));
194       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
195       // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
196       // Level.INFO.toString())));
197       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache.getDefault(
198               "logs.Jalview.level", Level.INFO.toString())));
199       // laxis.addAppender(ap);
200       // lcastor.addAppender(ap);
201       // jalview.bin.Cache.log.addAppender(ap);
202       // Tell the user that debug is enabled
203       jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
204     } catch (Exception ex)
205     {
206       System.err.println("Problems initializing the log4j system\n");
207       ex.printStackTrace(System.err);
208     }
209   }
210
211   /** Called when Jalview is started */
212   public static void loadProperties(String propsFile)
213   {
214     propertiesFile = propsFile;
215     if (propsFile == null)
216     {
217       propertiesFile = System.getProperty("user.home") + File.separatorChar
218               + ".jalview_properties";
219     }
220
221     try
222     {
223       FileInputStream fis = new FileInputStream(propertiesFile);
224       applicationProperties.load(fis);
225       applicationProperties.remove("LATEST_VERSION");
226       applicationProperties.remove("VERSION");
227       fis.close();
228     } catch (Exception ex)
229     {
230       System.out.println("Error reading properties file: " + ex);
231     }
232
233     if (getDefault("USE_PROXY", false))
234     {
235       System.out.println("Using proxyServer: "
236               + getDefault("PROXY_SERVER", null) + " proxyPort: "
237               + getDefault("PROXY_PORT", null));
238       System
239               .setProperty("http.proxyHost", getDefault("PROXY_SERVER",
240                       null));
241       System.setProperty("http.proxyPort", getDefault("PROXY_PORT", null));
242     }
243
244     // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
245     // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
246     // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
247     try
248     {
249       String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
250               .getCodeSource().getLocation().toString().concat(
251                       "!/.build_properties"));
252
253       java.net.URL localJarFileURL = new java.net.URL(buildDetails);
254
255       InputStream in = localJarFileURL.openStream();
256       applicationProperties.load(in);
257       in.close();
258     } catch (Exception ex)
259     {
260       System.out.println("Error reading build details: " + ex);
261       applicationProperties.remove("VERSION");
262     }
263
264     String jnlpVersion = System.getProperty("jalview.version");
265     String codeVersion = getProperty("VERSION");
266
267     if (codeVersion == null)
268     {
269       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
270       codeVersion = "Test";
271       jnlpVersion = "Test";
272     }
273
274     System.out.println("Jalview Version: " + codeVersion);
275
276     // jnlpVersion will be null if we're using InstallAnywhere
277     // Dont do this check if running in headless mode
278     if (jnlpVersion == null
279             && getDefault("VERSION_CHECK", true)
280             && (System.getProperty("java.awt.headless") == null || System
281                     .getProperty("java.awt.headless").equals("false")))
282     {
283
284       class VersionChecker extends Thread
285       {
286         public void run()
287         {
288           String orgtimeout = System
289                   .getProperty("sun.net.client.defaultConnectTimeout");
290           if (orgtimeout == null)
291           {
292             orgtimeout = "30";
293             System.out.println("# INFO: Setting default net timeout to "
294                     + orgtimeout + " seconds.");
295           }
296           String jnlpVersion = null;
297           try
298           {
299             System.setProperty("sun.net.client.defaultConnectTimeout",
300                     "5000");
301             java.net.URL url = new java.net.URL(
302                     "http://www.jalview.org/webstart/jalview.jnlp");
303             BufferedReader in = new BufferedReader(new InputStreamReader(
304                     url.openStream()));
305             String line = null;
306             while ((line = in.readLine()) != null)
307             {
308               if (line.indexOf("jalview.version") == -1)
309               {
310                 continue;
311               }
312
313               line = line.substring(line.indexOf("value=") + 7);
314               line = line.substring(0, line.lastIndexOf("\""));
315               jnlpVersion = line;
316               break;
317             }
318           } catch (Exception ex)
319           {
320             System.out
321                     .println("Non-fatal exceptions when checking version at www.jalview.org :");
322             System.out.println(ex);
323             jnlpVersion = getProperty("VERSION");
324           }
325           System.setProperty("sun.net.client.defaultConnectTimeout",
326                   orgtimeout);
327
328           setProperty("LATEST_VERSION", jnlpVersion);
329         }
330       }
331
332       VersionChecker vc = new VersionChecker();
333       vc.start();
334     }
335     else
336     {
337       if (jnlpVersion != null)
338       {
339         setProperty("LATEST_VERSION", jnlpVersion);
340       }
341       else
342       {
343         applicationProperties.remove("LATEST_VERSION");
344       }
345     }
346
347     setProperty("VERSION", codeVersion);
348
349     // LOAD USERDEFINED COLOURS
350     jalview.gui.UserDefinedColours
351             .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
352     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
353             false);
354   }
355
356   /**
357    * Gets Jalview application property of given key. Returns null if key not
358    * found
359    * 
360    * @param key
361    *          Name of property
362    * 
363    * @return Property value
364    */
365   public static String getProperty(String key)
366   {
367     return applicationProperties.getProperty(key);
368   }
369
370   /**
371    * These methods are used when checking if the saved preference is different
372    * to the default setting
373    */
374
375   public static boolean getDefault(String property, boolean def)
376   {
377     String string = getProperty(property);
378     if (string != null)
379     {
380       def = Boolean.valueOf(string).booleanValue();
381     }
382
383     return def;
384   }
385
386   /**
387    * These methods are used when checking if the saved preference is different
388    * to the default setting
389    */
390   public static String getDefault(String property, String def)
391   {
392     String string = getProperty(property);
393     if (string != null)
394     {
395       return string;
396     }
397
398     return def;
399   }
400
401   /**
402    * Stores property in the file "HOME_DIR/.jalview_properties"
403    * 
404    * @param key
405    *          Name of object
406    * @param obj
407    *          String value of property
408    * 
409    * @return String value of property
410    */
411   public static String setProperty(String key, String obj)
412   {
413     try
414     {
415       FileOutputStream out = new FileOutputStream(propertiesFile);
416       applicationProperties.setProperty(key, obj);
417       applicationProperties.store(out, "---JalviewX Properties File---");
418       out.close();
419     } catch (Exception ex)
420     {
421       System.out.println("Error setting property: " + key + " " + obj
422               + "\n" + ex);
423     }
424     return obj;
425   }
426
427   /**
428    * remove the specified property from the jalview properties file
429    * 
430    * @param string
431    */
432   public static void removeProperty(String string)
433   {
434     applicationProperties.remove(string);
435     saveProperties();
436   }
437
438   /**
439    * save the properties to the jalview properties path
440    */
441   public static void saveProperties()
442   {
443     try
444     {
445       FileOutputStream out = new FileOutputStream(propertiesFile);
446       applicationProperties.store(out, "---JalviewX Properties File---");
447       out.close();
448     } catch (Exception ex)
449     {
450       System.out.println("Error saving properties: " + ex);
451     }
452   }
453
454   /**
455    * internal vamsas class discovery state
456    */
457   private static int vamsasJarsArePresent = -1;
458
459   /**
460    * Searches for vamsas client classes on class path.
461    * 
462    * @return true if vamsas client is present on classpath
463    */
464   public static boolean vamsasJarsPresent()
465   {
466     if (vamsasJarsArePresent == -1)
467     {
468       try
469       {
470         if (jalview.jbgui.GDesktop.class.getClassLoader().loadClass(
471                 "uk.ac.vamsas.client.VorbaId") != null)
472         {
473           jalview.bin.Cache.log
474                   .debug("Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
475           vamsasJarsArePresent = 1;
476           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
477           lvclient.setLevel(Level.toLevel(Cache.getDefault(
478                   "logs.Vamsas.Level", Level.INFO.toString())));
479
480           lvclient.addAppender(log.getAppender("JalviewLogger"));
481           // Tell the user that debug is enabled
482           lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
483         }
484       } catch (Exception e)
485       {
486         vamsasJarsArePresent = 0;
487         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
488       }
489     }
490     return (vamsasJarsArePresent > 0);
491   }
492
493   /**
494    * internal vamsas class discovery state
495    */
496   private static int groovyJarsArePresent = -1;
497
498   /**
499    * Searches for vamsas client classes on class path.
500    * 
501    * @return true if vamsas client is present on classpath
502    */
503   public static boolean groovyJarsPresent()
504   {
505     if (groovyJarsArePresent == -1)
506     {
507       try
508       {
509         if (Cache.class.getClassLoader().loadClass(
510                 "groovy.lang.GroovyObject") != null)
511         {
512           jalview.bin.Cache.log
513                   .debug("Found Groovy (groovy.lang.GroovyObject can be loaded)");
514           groovyJarsArePresent = 1;
515           Logger lgclient = Logger.getLogger("groovy");
516           lgclient.setLevel(Level.toLevel(Cache.getDefault(
517                   "logs.Groovy.Level", Level.INFO.toString())));
518
519           lgclient.addAppender(log.getAppender("JalviewLogger"));
520           // Tell the user that debug is enabled
521           lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
522         }
523       } catch (Error e)
524       {
525         groovyJarsArePresent = 0;
526         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
527       } catch (Exception e)
528       {
529         groovyJarsArePresent = 0;
530         jalview.bin.Cache.log.debug("Groovy Classes are not present");
531       }
532     }
533     return (groovyJarsArePresent > 0);
534   }
535
536   /**
537    * generate Das1Sources from the local das source list
538    * 
539    * @return Vector of Das1Sources
540    */
541   public static Vector getLocalDasSources()
542   {
543     Vector localSources = new Vector();
544     String local = jalview.bin.Cache.getProperty("DAS_LOCAL_SOURCE");
545     if (local != null)
546     {
547       StringTokenizer st = new StringTokenizer(local, "\t");
548       while (st.hasMoreTokens())
549       {
550         String token = st.nextToken();
551         int bar = token.indexOf("|");
552         Das1Source source = new Das1Source();
553         source.setUrl(token.substring(bar + 1));
554         if (source.getUrl().startsWith("sequence:"))
555         {
556           source.setUrl(source.getUrl().substring(9));
557           // this source also serves sequences as well as features
558           source.setCapabilities(new String[]
559           { "sequence", "features" });
560         }
561         else
562         {
563           // default is that all user added sources serve features
564           source.setCapabilities(new String[]
565           { "features" });
566         }
567
568         source.setNickname(token.substring(0, bar));
569
570         localSources.addElement(source);
571       }
572     }
573     return localSources;
574   }
575
576   /**
577    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
578    * enabled.
579    */
580   protected static Object tracker = null;
581
582   protected static Class trackerfocus = null;
583
584   protected static Class jgoogleanalyticstracker = null;
585
586   /**
587    * Initialise the google tracker if it is not done already.
588    */
589   public static void initGoogleTracker()
590   {
591     if (tracker == null)
592     {
593       if (jgoogleanalyticstracker == null)
594       {
595         // try to get the tracker class
596         try
597         {
598           jgoogleanalyticstracker = Cache.class
599                   .getClassLoader()
600                   .loadClass(
601                           "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
602           trackerfocus = Cache.class.getClassLoader().loadClass(
603                   "com.boxysystems.jgoogleanalytics.FocusPoint");
604         } catch (Exception e)
605         {
606           log
607                   .debug("com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
608           tracker = null;
609           jgoogleanalyticstracker = null;
610           trackerfocus = null;
611           return;
612         }
613       }
614       // now initialise tracker
615       Exception re = null, ex = null;
616       Error err = null;
617       String vrs = "No Version Accessible";
618       try
619       {
620         // Google analytics tracking code for Library Finder
621         tracker = jgoogleanalyticstracker.getConstructor(new Class[]
622         { String.class, String.class, String.class }).newInstance(
623                 new Object[]
624                 {
625                     "Jalview Desktop",
626                     (vrs = jalview.bin.Cache.getProperty("VERSION")
627                             + "_"
628                             + jalview.bin.Cache.getDefault("BUILD_DATE",
629                                     "unknown")), "UA-9060947-1" });
630         jgoogleanalyticstracker.getMethod("trackAsynchronously",
631                 new Class[]
632                 { trackerfocus }).invoke(tracker, new Object[]
633         { trackerfocus.getConstructor(new Class[]
634         { String.class }).newInstance(new Object[]
635         { "Application Started." }) });
636       } catch (RuntimeException e)
637       {
638         re = e;
639       } catch (Exception e)
640       {
641         ex = e;
642       } catch (Error e)
643       {
644         err = e;
645       }
646       if (re != null || ex != null || err != null)
647       {
648         if (log != null)
649         {
650           if (re != null)
651             log
652                     .debug(
653                             "Caught runtime exception in googletracker init:",
654                             re);
655           if (ex != null)
656             log.warn(
657                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
658                             + vrs, ex);
659           if (err != null)
660             log.error(
661                     "Whilst initing GoogleTracker for Jalview Desktop version "
662                             + vrs, err);
663         }
664         else
665         {
666           if (re != null)
667           {
668             System.err
669                     .println("Debug: Caught runtime exception in googletracker init:"
670                             + vrs);
671             re.printStackTrace();
672           }
673           if (ex != null)
674           {
675             System.err
676                     .println("Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
677                             + vrs);
678             ex.printStackTrace();
679           }
680
681           if (err != null)
682           {
683             System.err
684                     .println("ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
685                             + vrs);
686             err.printStackTrace();
687           }
688         }
689       }
690       else
691       {
692         log.debug("Successfully initialised tracker.");
693       }
694     }
695   }
696
697 }