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