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