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