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