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