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