2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.Color;
24 import java.io.BufferedReader;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.PrintWriter;
31 import java.io.StringWriter;
32 import java.net.Authenticator;
33 import java.net.PasswordAuthentication;
34 import java.text.DateFormat;
35 import java.text.SimpleDateFormat;
36 import java.util.Collections;
37 import java.util.Date;
38 import java.util.Enumeration;
39 import java.util.Locale;
40 import java.util.Properties;
41 import java.util.StringTokenizer;
42 import java.util.TreeSet;
43 import java.util.regex.Pattern;
45 import javax.swing.LookAndFeel;
46 import javax.swing.UIManager;
48 import org.apache.log4j.ConsoleAppender;
49 import org.apache.log4j.Level;
50 import org.apache.log4j.Logger;
51 import org.apache.log4j.SimpleLayout;
53 import jalview.datamodel.PDBEntry;
54 import jalview.gui.Preferences;
55 import jalview.gui.UserDefinedColours;
56 import jalview.jbgui.GPreferences;
57 import jalview.schemes.ColourSchemeLoader;
58 import jalview.schemes.ColourSchemes;
59 import jalview.schemes.UserColourScheme;
60 import jalview.structure.StructureImportSettings;
61 import jalview.urls.IdOrgSettings;
62 import jalview.util.ColorUtils;
63 import jalview.util.MessageManager;
64 import jalview.ws.sifts.SiftsSettings;
67 * Stores and retrieves Jalview Application Properties Lists and fields within
68 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
69 * are alternative values for a tag. <br>
71 * Current properties include:
74 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
75 * logging level for axis (used for web services) <br>
77 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
78 * the logging level for castor (used for serialization) <br>
80 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
82 * <li>SCREEN_WIDTH</li>
83 * <li>SCREEN_HEIGHT</li>
84 * <li>SCREEN_Y=285</li>
85 * <li>SCREEN_X=371</li>
86 * <li>SHOW_FULLSCREEN boolean</li>
87 * <li>FONT_NAME java font name for alignment text display</li>
88 * <li>FONT_SIZE size of displayed alignment text</li>
89 * <li>FONT_STYLE style of font displayed (sequence labels are always
91 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
92 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
93 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
94 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
95 * <li>SHOW_IDENTITY show percentage identity annotation</li>
96 * <li>SHOW_QUALITY show alignment quality annotation</li>
97 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
98 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
99 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
100 * LABEL_AND_SEQUENCE</li>
101 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
102 * sequence annotations</li>
103 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
104 * annotation row</li>
105 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
106 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
107 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
108 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
109 * <li>VERSION the version of the jalview build</li>
110 * <li>BUILD_DATE date of this build</li>
111 * <li>LATEST_VERSION the latest jalview version advertised on the
112 * www.jalview.org</li>
113 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
115 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
116 * suffix to file</li>
117 * <li>RECENT_URL list of recently retrieved URLs</li>
118 * <li>RECENT_FILE list of recently opened files</li>
119 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
120 * <li>PROXY_SERVER the proxy</li>
121 * <li>PROXY_PORT</li>
122 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
124 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
126 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
127 * collecting usage statistics</li>
128 * <li>SHOW_OVERVIEW boolean for overview window display</li>
129 * <li>ANTI_ALIAS boolean for smooth fonts</li>
130 * <li>RIGHT_ALIGN_IDS boolean</li>
131 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
132 * <li>PAD_GAPS boolean</li>
133 * <li>ID_ITALICS boolean</li>
134 * <li>SHOW_JV_SUFFIX</li>
135 * <li>WRAP_ALIGNMENT</li>
136 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
138 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
139 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
141 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
143 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
144 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
145 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
146 * jalview.utils.GroupURLLink for more info</li>
147 * <li>DEFAULT_BROWSER for unix</li>
148 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
150 * <li>VERSION_CHECK (true) check for the latest release version from
151 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
152 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
154 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
156 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
157 * displayed as '.'</li>
158 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
159 * order of a newly displayed tree</li>
160 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
161 * sequence ID strings before attempting retrieval from any datasource</li>
162 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
164 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
165 * in the alignment.</li>
166 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
168 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
170 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
171 * logo normalised to row height rather than histogram height.</li>
172 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
173 * respond to selections made in other alignments containing the same sequences.
175 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
176 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
177 * warning dialog box is displayed.</li>
178 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
179 * when shading by annotation</li>
180 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
181 * when shading by annotation</li>
182 * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
183 * requests to be redirected to a mirror of http://www.jalview.org</li>
184 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
185 * alignment figure to accommodate even the longest sequence ID or annotation
187 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
188 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
189 * will override this).</li>
190 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
192 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
193 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
195 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
197 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
199 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
200 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
204 * Deprecated settings:
207 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
208 * startup (JWS1 services only)</li>
209 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
210 * (JWS1 services only)</li>
211 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
212 * services in the desktop GUI</li>
213 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
214 * panel in web service preferences</li>
218 * @version $Revision$
223 * property giving log4j level for CASTOR loggers
225 public static final String CASTORLOGLEVEL = "logs.Castor.level";
228 * property giving log4j level for AXIS loggers
230 public static final String AXISLOGLEVEL = "logs.Axis.level";
233 * property giving log4j level for Jalview Log
235 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
240 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
241 .getProperty("user.home") + File.separatorChar
242 + ".sifts_downloads" + File.separatorChar;
244 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
246 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
249 * Identifiers.org download settings
251 private static final String ID_ORG_FILE = System.getProperty("user.home")
252 + File.separatorChar + ".identifiers.org.ids.json";
255 * Allowed values are PDB or mmCIF
257 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
260 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
264 * a date formatter using a fixed (rather than the user's) locale;
265 * this ensures that date properties can be written and re-read successfully
266 * even if the user changes their locale setting
268 private static final DateFormat date_format = SimpleDateFormat
269 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
270 SimpleDateFormat.MEDIUM, Locale.UK);
273 * Initialises the Jalview Application Log
275 public static Logger log;
277 // save the proxy properties set at startup
278 public final static String[] startupProxyProperties = {
279 System.getProperty("http.proxyHost"),
280 System.getProperty("http.proxyPort"),
281 System.getProperty("https.proxyHost"),
282 System.getProperty("https.proxyPort"),
283 System.getProperty("http.proxyUser"),
284 System.getProperty("http.proxyPassword"),
285 System.getProperty("https.proxyUser"),
286 System.getProperty("https.proxyPassword"),
287 System.getProperty("http.nonProxyHosts") };
289 public final static String PROXYTYPE_NONE = "none";
291 // "false" and "true" for backward compatibility
292 public final static String PROXYTYPE_SYSTEM = "false";
294 public final static String PROXYTYPE_CUSTOM = "true";
296 // in-memory only storage of proxy password, safer to use char array
297 public static char[] proxyAuthPassword = null;
299 /** Jalview Properties */
300 public static Properties applicationProperties = new Properties()
302 // override results in properties output in alphabetical order
304 public synchronized Enumeration<Object> keys()
306 return Collections.enumeration(new TreeSet<>(super.keySet()));
310 /** Default file is ~/.jalview_properties */
311 static String propertiesFile;
313 private static boolean propsAreReadOnly = false;
315 public static void initLogger()
323 // TODO: redirect stdout and stderr here in order to grab the output of
326 ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
328 ap.setName("JalviewLogger");
329 org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
331 Logger laxis = Logger.getLogger("org.apache.axis");
332 Logger lcastor = Logger.getLogger("org.exolab.castor");
333 jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
335 laxis.setLevel(Level.toLevel(
336 Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
337 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
338 Level.INFO.toString())));
339 lcastor = Logger.getLogger("org.exolab.castor.xml");
340 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
341 Level.INFO.toString())));
342 // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
343 // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
344 // Level.INFO.toString())));
345 jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
346 .getDefault("logs.Jalview.level", Level.INFO.toString())));
347 // laxis.addAppender(ap);
348 // lcastor.addAppender(ap);
349 // jalview.bin.Cache.log.addAppender(ap);
350 // Tell the user that debug is enabled
351 jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
352 } catch (Exception ex)
354 System.err.println("Problems initializing the log4j system\n");
355 ex.printStackTrace(System.err);
360 * Loads properties from the given properties file. Any existing properties
363 public static void loadProperties(String propsFile)
365 propertiesFile = propsFile;
366 if (propsFile == null)
368 propertiesFile = System.getProperty("user.home") + File.separatorChar
369 + ".jalview_properties";
373 // don't corrupt the file we've been given.
374 propsAreReadOnly = true;
382 fis = new java.net.URL(propertiesFile).openStream();
384 "Loading jalview properties from : " + propertiesFile);
386 "Disabling Jalview writing to user's local properties file.");
387 propsAreReadOnly = true;
389 } catch (Exception ex)
395 fis = new FileInputStream(propertiesFile);
397 applicationProperties.clear();
398 applicationProperties.load(fis);
400 // remove any old build properties
402 deleteBuildProperties();
404 } catch (Exception ex)
406 System.out.println("Error reading properties file: " + ex);
409 // PROXY TYPE settings (now three options "none", "false", "true", but using
410 // backward compatible strings)
411 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
412 // default to upgrading old settings
416 clearProxyProperties();
418 case PROXYTYPE_SYSTEM: // use system settings
419 resetProxyProperties();
421 case PROXYTYPE_CUSTOM: // use specified proxy settings
422 String httpHost = getDefault("PROXY_SERVER", "");
423 String httpPort = getDefault("PROXY_PORT", "8080");
424 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
425 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
426 String httpUser = getDefault("PROXY_AUTH_USER", null);
427 // https.proxyUser and https.proxyPassword are not able to be
428 // independently set in Preferences yet (or http.nonProxyHosts)
429 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
430 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
431 proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
434 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
439 // LOAD THE AUTHORS FROM THE authors.props file
442 String authorDetails = "jar:"
443 .concat(Cache.class.getProtectionDomain().getCodeSource()
444 .getLocation().toString().concat("!/authors.props"));
446 java.net.URL localJarFileURL = new java.net.URL(authorDetails);
448 InputStream in = localJarFileURL.openStream();
449 applicationProperties.load(in);
451 } catch (Exception ex)
453 System.out.println("Error reading author details: " + ex);
454 applicationProperties.remove("AUTHORS");
455 applicationProperties.remove("AUTHORFNAMES");
456 applicationProperties.remove("YEAR");
459 loadBuildProperties(false);
462 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
464 SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
465 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
467 SiftsSettings.setFailSafePIDThreshold(
468 jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
469 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
471 SiftsSettings.setCacheThresholdInDays(
472 jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
473 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
475 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
476 "http://www.jalview.org/services/identifiers"));
477 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
479 StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
480 .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
481 StructureImportSettings
482 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
483 // StructureImportSettings
484 // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
485 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
487 String jnlpVersion = System.getProperty("jalview.version");
489 // jnlpVersion will be null if a latest version check for the channel needs
491 // Dont do this check if running in headless mode
493 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
494 && (System.getProperty("java.awt.headless") == null || System
495 .getProperty("java.awt.headless").equals("false")))
498 class VersionChecker extends Thread
503 String orgtimeout = System
504 .getProperty("sun.net.client.defaultConnectTimeout");
505 if (orgtimeout == null)
508 System.out.println("# INFO: Setting default net timeout to "
509 + orgtimeout + " seconds.");
511 String remoteVersion = null;
514 System.setProperty("sun.net.client.defaultConnectTimeout",
516 java.net.URL url = new java.net.URL(Cache
517 .getDefault("www.jalview.org", "http://www.jalview.org")
518 + "/webstart/jalview.jnlp");
519 BufferedReader in = new BufferedReader(
520 new InputStreamReader(url.openStream()));
522 while ((line = in.readLine()) != null)
524 if (line.indexOf("jalview.version") == -1)
529 line = line.substring(line.indexOf("value=") + 7);
530 line = line.substring(0, line.lastIndexOf("\""));
531 remoteVersion = line;
534 } catch (Exception ex)
537 "Non-fatal exception when checking version at www.jalview.org :");
538 System.out.println(ex);
539 remoteVersion = getProperty("VERSION");
541 System.setProperty("sun.net.client.defaultConnectTimeout",
544 setProperty("LATEST_VERSION", remoteVersion);
548 VersionChecker vc = new VersionChecker();
553 if (jnlpVersion != null)
555 setProperty("LATEST_VERSION", jnlpVersion);
559 applicationProperties.remove("LATEST_VERSION");
563 // LOAD USERDEFINED COLOURS
565 .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
566 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
570 public static void loadBuildProperties(boolean reportVersion)
572 String codeInstallation = getProperty("INSTALLATION");
573 boolean printV = codeInstallation == null;
575 // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
578 String buildDetails = "jar:".concat(Cache.class.getProtectionDomain()
579 .getCodeSource().getLocation().toString()
580 .concat("!/.build_properties"));
582 java.net.URL localJarFileURL = new java.net.URL(buildDetails);
584 InputStream in = localJarFileURL.openStream();
585 applicationProperties.load(in);
587 } catch (Exception ex)
589 System.out.println("Error reading build details: " + ex);
590 applicationProperties.remove("VERSION");
592 String codeVersion = getProperty("VERSION");
593 codeInstallation = getProperty("INSTALLATION");
595 if (codeVersion == null)
597 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
598 codeVersion = "Test";
599 codeInstallation = "";
603 codeInstallation = " (" + codeInstallation + ")";
605 setProperty("VERSION", codeVersion);
606 new BuildDetails(codeVersion, null, codeInstallation);
607 if (printV && reportVersion)
610 "Jalview Version: " + codeVersion + codeInstallation);
614 private static void deleteBuildProperties()
616 applicationProperties.remove("LATEST_VERSION");
617 applicationProperties.remove("VERSION");
618 applicationProperties.remove("AUTHORS");
619 applicationProperties.remove("AUTHORFNAMES");
620 applicationProperties.remove("YEAR");
621 applicationProperties.remove("BUILD_DATE");
622 applicationProperties.remove("INSTALLATION");
626 * Gets Jalview application property of given key. Returns null if key not
632 * @return Property value
634 public static String getProperty(String key)
636 return applicationProperties.getProperty(key);
640 * These methods are used when checking if the saved preference is different
641 * to the default setting
644 public static boolean getDefault(String property, boolean def)
646 String string = getProperty(property);
649 def = Boolean.valueOf(string).booleanValue();
655 public static int getDefault(String property, int def)
657 String string = getProperty(property);
662 def = Integer.parseInt(string);
663 } catch (NumberFormatException e)
665 System.out.println("Error parsing int property '" + property
666 + "' with value '" + string + "'");
674 * These methods are used when checking if the saved preference is different
675 * to the default setting
677 public static String getDefault(String property, String def)
679 String string = getProperty(property);
689 * Stores property in the file "HOME_DIR/.jalview_properties"
694 * String value of property
696 * @return previous value of property (or null)
698 public static Object setProperty(String key, String obj)
700 Object oldValue = null;
703 oldValue = applicationProperties.setProperty(key, obj);
704 if (propertiesFile != null && !propsAreReadOnly)
706 FileOutputStream out = new FileOutputStream(propertiesFile);
707 applicationProperties.store(out, "---JalviewX Properties File---");
710 } catch (Exception ex)
713 "Error setting property: " + key + " " + obj + "\n" + ex);
719 * remove the specified property from the jalview properties file
723 public static void removeProperty(String string)
725 applicationProperties.remove(string);
730 * save the properties to the jalview properties path
732 public static void saveProperties()
734 if (!propsAreReadOnly)
738 FileOutputStream out = new FileOutputStream(propertiesFile);
739 applicationProperties.store(out, "---JalviewX Properties File---");
741 } catch (Exception ex)
743 System.out.println("Error saving properties: " + ex);
749 * internal vamsas class discovery state
751 private static int vamsasJarsArePresent = -1;
754 * Searches for vamsas client classes on class path.
756 * @return true if vamsas client is present on classpath
758 public static boolean vamsasJarsPresent()
760 if (vamsasJarsArePresent == -1)
764 if (jalview.jbgui.GDesktop.class.getClassLoader()
765 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
767 jalview.bin.Cache.log.debug(
768 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
769 vamsasJarsArePresent = 1;
770 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
771 lvclient.setLevel(Level.toLevel(Cache
772 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
774 lvclient.addAppender(log.getAppender("JalviewLogger"));
775 // Tell the user that debug is enabled
776 lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
778 } catch (Exception e)
780 vamsasJarsArePresent = 0;
781 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
784 return (vamsasJarsArePresent > 0);
788 * internal vamsas class discovery state
790 private static int groovyJarsArePresent = -1;
793 * Searches for vamsas client classes on class path.
795 * @return true if vamsas client is present on classpath
797 public static boolean groovyJarsPresent()
799 if (groovyJarsArePresent == -1)
803 if (Cache.class.getClassLoader()
804 .loadClass("groovy.lang.GroovyObject") != null)
806 jalview.bin.Cache.log.debug(
807 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
808 groovyJarsArePresent = 1;
809 Logger lgclient = Logger.getLogger("groovy");
810 lgclient.setLevel(Level.toLevel(Cache
811 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
813 lgclient.addAppender(log.getAppender("JalviewLogger"));
814 // Tell the user that debug is enabled
815 lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
819 groovyJarsArePresent = 0;
820 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
821 } catch (Exception e)
823 groovyJarsArePresent = 0;
824 jalview.bin.Cache.log.debug("Groovy Classes are not present");
827 return (groovyJarsArePresent > 0);
831 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
834 protected static Object tracker = null;
836 protected static Class trackerfocus = null;
838 protected static Class jgoogleanalyticstracker = null;
841 * Initialise the google tracker if it is not done already.
843 public static void initGoogleTracker()
847 if (jgoogleanalyticstracker == null)
849 // try to get the tracker class
852 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
853 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
854 trackerfocus = Cache.class.getClassLoader()
855 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
856 } catch (Exception e)
859 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
861 jgoogleanalyticstracker = null;
866 // now initialise tracker
867 Exception re = null, ex = null;
869 String vrs = "No Version Accessible";
872 // Google analytics tracking code for Library Finder
873 tracker = jgoogleanalyticstracker
874 .getConstructor(new Class[]
875 { String.class, String.class, String.class })
876 .newInstance(new Object[]
878 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
879 + jalview.bin.Cache.getDefault("BUILD_DATE",
882 jgoogleanalyticstracker
883 .getMethod("trackAsynchronously", new Class[]
885 .invoke(tracker, new Object[]
886 { trackerfocus.getConstructor(new Class[] { String.class })
887 .newInstance(new Object[]
888 { "Application Started." }) });
889 } catch (RuntimeException e)
892 } catch (Exception e)
899 if (re != null || ex != null || err != null)
905 log.debug("Caught runtime exception in googletracker init:",
911 "Failed to initialise GoogleTracker for Jalview Desktop with version "
918 "Whilst initing GoogleTracker for Jalview Desktop version "
928 "Debug: Caught runtime exception in googletracker init:"
930 re.printStackTrace();
935 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
937 ex.printStackTrace();
943 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
945 err.printStackTrace();
951 log.debug("Successfully initialised tracker.");
957 * get the user's default colour if available
963 public static Color getDefaultColour(String property, Color defcolour)
965 String colprop = getProperty(property);
970 Color col = ColorUtils.parseColourString(colprop);
973 log.warn("Couldn't parse '" + colprop + "' as a colour for "
976 return (col == null) ? defcolour : col;
980 * store a colour as a Jalview user default property
985 public static void setColourProperty(String property, Color colour)
987 setProperty(property, jalview.util.Format.getHexString(colour));
991 * Stores a formatted date in a jalview property, using a fixed locale.
993 * @param propertyName
995 * @return the formatted date string
997 public static String setDateProperty(String propertyName, Date date)
999 String formatted = date_format.format(date);
1000 setProperty(propertyName, formatted);
1005 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1006 * format) and returns as a Date, or null if parsing fails
1008 * @param propertyName
1012 public static Date getDateProperty(String propertyName)
1014 String val = getProperty(propertyName);
1019 return date_format.parse(val);
1020 } catch (Exception ex)
1022 System.err.println("Invalid or corrupt date in property '"
1023 + propertyName + "' : value was '" + val + "'");
1030 * get and parse a property as an integer. send any parsing problems to
1034 * @return null or Integer
1036 public static Integer getIntegerProperty(String property)
1038 String val = getProperty(property);
1039 if (val != null && (val = val.trim()).length() > 0)
1043 return Integer.valueOf(val);
1044 } catch (NumberFormatException x)
1046 System.err.println("Invalid integer in property '" + property
1047 + "' (value was '" + val + "')");
1054 * Set the specified value, or remove it if null or empty. Does not save the
1060 public static void setOrRemove(String propName, String value)
1062 if (propName == null)
1066 if (value == null || value.trim().length() < 1)
1068 Cache.applicationProperties.remove(propName);
1072 Cache.applicationProperties.setProperty(propName, value);
1077 * Loads in user colour schemes from files.
1080 * a '|'-delimited list of file paths
1082 public static void initUserColourSchemes(String files)
1084 if (files == null || files.length() == 0)
1089 // In case colours can't be loaded, we'll remove them
1090 // from the default list here.
1091 StringBuffer coloursFound = new StringBuffer();
1092 StringTokenizer st = new StringTokenizer(files, "|");
1093 while (st.hasMoreElements())
1095 String file = st.nextToken();
1098 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1101 if (coloursFound.length() > 0)
1103 coloursFound.append("|");
1105 coloursFound.append(file);
1106 ColourSchemes.getInstance().registerColourScheme(ucs);
1108 } catch (Exception ex)
1110 System.out.println("Error loading User ColourFile\n" + ex);
1113 if (!files.equals(coloursFound.toString()))
1115 if (coloursFound.toString().length() > 1)
1117 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1118 coloursFound.toString());
1122 applicationProperties
1123 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1129 * Initial logging information helper for various versions output
1133 * @param defaultValue
1135 private static void appendIfNotNull(StringBuilder sb, String prefix,
1136 String value, String suffix, String defaultValue)
1138 if (value == null && defaultValue == null)
1142 String line = prefix + (value != null ? value : defaultValue) + suffix;
1148 * @return Jalview version, build details and JVM platform version for console
1150 public static String getVersionDetailsForConsole()
1152 StringBuilder sb = new StringBuilder();
1153 sb.append("Jalview Version: ");
1154 sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1156 sb.append("Jalview Installation: ");
1157 sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1159 sb.append("Build Date: ");
1160 sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1162 sb.append("Java version: ");
1163 sb.append(System.getProperty("java.version"));
1165 sb.append(System.getProperty("os.arch"));
1167 sb.append(System.getProperty("os.name"));
1169 sb.append(System.getProperty("os.version"));
1171 appendIfNotNull(sb, "Install4j version: ",
1172 System.getProperty("sys.install4jVersion"), "\n", null);
1173 appendIfNotNull(sb, "Install4j template version: ",
1174 System.getProperty("installer_template_version"), "\n", null);
1175 appendIfNotNull(sb, "Launcher version: ",
1176 System.getProperty("launcher_version"), "\n", null);
1177 LookAndFeel laf = UIManager.getLookAndFeel();
1178 String lafName = laf == null ? "Not obtained" : laf.getName();
1179 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1180 sb.append("LookAndFeel: ");
1183 sb.append(lafClass);
1185 // Not displayed in release version ( determined by possible version number
1186 // regex 9[9.]*9[.-_a9]* )
1187 if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1188 jalview.bin.Cache.getDefault("VERSION", "TEST")))
1190 appendIfNotNull(sb, "Getdown appdir: ",
1191 System.getProperty("getdownappdir"), "\n", null);
1192 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1195 return sb.toString();
1200 * @return build details as reported in splashscreen
1202 public static String getBuildDetailsForSplash()
1204 // consider returning more human friendly info
1205 // eg 'built from Source' or update channel
1206 return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1209 public static String getStackTraceString(Throwable t)
1211 StringWriter sw = new StringWriter();
1212 PrintWriter pw = new PrintWriter(sw);
1213 t.printStackTrace(pw);
1214 return sw.toString();
1217 // proxy properties methods
1218 public static void clearProxyProperties()
1220 setProxyProperties(null, null, null, null, null, null, null, null,
1224 public static void resetProxyProperties()
1226 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1227 startupProxyProperties[2], startupProxyProperties[3],
1228 startupProxyProperties[4],
1229 startupProxyProperties[5].toCharArray(),
1230 startupProxyProperties[6],
1231 startupProxyProperties[7].toCharArray(),
1232 startupProxyProperties[8]);
1233 StringBuilder sb = new StringBuilder();
1234 sb.append("Setting proxy properties to: http.proxyHost=")
1235 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1236 .append(startupProxyProperties[1])
1237 .append(startupProxyProperties[4] != null
1238 && !startupProxyProperties[4].isEmpty()
1239 ? " [" + startupProxyProperties[4] + "]"
1241 .append(", https.proxyHost=").append(startupProxyProperties[2])
1242 .append(", https.proxyPort=").append(startupProxyProperties[3])
1243 .append(startupProxyProperties[6] != null
1244 && !startupProxyProperties[6].isEmpty()
1245 ? " [" + startupProxyProperties[6] + "]"
1248 Cache.debug(sb.toString());
1251 public static void setProxyProperties(String httpHost, String httpPort,
1252 String httpsHost, String httpsPort, String httpUser,
1253 char[] httpPassword, String httpsUser, char[] httpsPassword,
1254 String nonProxyHosts)
1256 setOrClearSystemProperty("http.proxyHost", httpHost);
1257 setOrClearSystemProperty("http.proxyPort", httpPort);
1258 setOrClearSystemProperty("https.proxyHost", httpsHost);
1259 setOrClearSystemProperty("https.proxyPort", httpsPort);
1260 setOrClearSystemProperty("http.proxyUser", httpUser);
1261 setOrClearSystemProperty("http.proxyPassword", httpPassword);
1262 setOrClearSystemProperty("https.proxyUser", httpsUser);
1263 setOrClearSystemProperty("https.proxyPassword", httpsPassword);
1264 // are we using a custom proxy (password prompt might be required)?
1265 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1266 .equals(PROXYTYPE_CUSTOM);
1267 if (httpUser != null || httpsUser != null)
1271 Authenticator.setDefault(new Authenticator()
1274 protected PasswordAuthentication getPasswordAuthentication()
1276 if (getRequestorType() == RequestorType.PROXY)
1278 String scheme = getRequestingScheme();
1279 boolean needProxyPasswordSet = false;
1280 if (customProxySet &&
1281 // we have a username but no password for the scheme being
1283 (scheme.equalsIgnoreCase("http")
1284 && (httpUser != null && httpUser.length() > 0
1285 && (httpPassword == null
1286 || httpPassword.length == 0)))
1287 || (scheme.equalsIgnoreCase("https")
1288 && (httpsUser != null
1289 && httpsUser.length() > 0
1290 && (httpsPassword == null
1291 || httpsPassword.length == 0))))
1293 // open Preferences -> Connections
1294 String message = MessageManager
1295 .getString("label.proxy_password_required");
1296 openPreferencesConnectionsForProxyPassword(message);
1302 if (scheme.equalsIgnoreCase("http")
1303 && getRequestingHost().equalsIgnoreCase(httpHost)
1304 && getRequestingPort() == Integer
1307 return new PasswordAuthentication(httpUser,
1310 if (scheme.equalsIgnoreCase("https")
1311 && getRequestingHost().equalsIgnoreCase(httpsHost)
1312 && getRequestingPort() == Integer
1313 .valueOf(httpsPort))
1315 return new PasswordAuthentication(httpsUser,
1318 } catch (NumberFormatException e)
1320 Cache.error("Problem with proxy port values [http:"
1321 + httpPort + ", https:" + httpsPort + "]");
1325 // non proxy request
1329 // required to re-enable basic authentication (should be okay for a
1331 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1332 } catch (SecurityException e)
1334 Cache.error("Could not set default Authenticator");
1335 Cache.debug(getStackTraceString(e));
1340 // reset the Authenticator to protect http.proxyUser and
1341 // http.proxyPassword Just In Case
1342 Authenticator.setDefault(null);
1345 // nonProxyHosts not currently configurable in Preferences
1346 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1349 private static void openPreferencesConnectionsForProxyPassword(
1353 Cache.info("Opening Preferences for proxy password");
1354 // Desktop.instance.preferences_actionPerformed(null);
1355 Preferences p = new Preferences(GPreferences.CONNECTIONS_TAB);
1359 public static void setOrClearSystemProperty(String key, char[] value)
1361 setOrClearSystemProperty(key,
1362 (value == null) ? null : value.toString());
1365 public static void setOrClearSystemProperty(String key, String value)
1373 System.clearProperty(key);
1377 System.setProperty(key, value);
1381 public final static int DEBUG = 10;
1383 public final static int INFO = 20;
1385 public final static int WARN = 30;
1387 public final static int ERROR = 40;
1389 public static boolean println(int level, String message)
1391 if (Cache.log == null)
1394 System.err.println(message);
1396 System.out.println(message);
1401 Cache.log.warn(message);
1403 else if (level >= INFO)
1405 Cache.log.info(message);
1409 Cache.log.debug(message);
1414 public static void debug(String message)
1416 println(DEBUG, message);
1419 public static void info(String message)
1421 println(INFO, message);
1424 public static void warn(String message)
1426 println(WARN, message);
1429 public static void error(String message)
1431 println(ERROR, message);