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