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