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