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