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;
33 import java.text.DateFormat;
34 import java.text.SimpleDateFormat;
35 import java.util.Collections;
36 import java.util.Date;
37 import java.util.Enumeration;
38 import java.util.Locale;
39 import java.util.Properties;
40 import java.util.StringTokenizer;
41 import java.util.TreeSet;
42 import java.util.regex.Pattern;
44 import javax.swing.LookAndFeel;
45 import javax.swing.UIManager;
47 import org.apache.log4j.ConsoleAppender;
48 import org.apache.log4j.Level;
49 import org.apache.log4j.Logger;
50 import org.apache.log4j.SimpleLayout;
52 import jalview.datamodel.PDBEntry;
53 import jalview.gui.UserDefinedColours;
54 import jalview.schemes.ColourSchemeLoader;
55 import jalview.schemes.ColourSchemes;
56 import jalview.schemes.UserColourScheme;
57 import jalview.structure.StructureImportSettings;
58 import jalview.urls.IdOrgSettings;
59 import jalview.util.ColorUtils;
60 import jalview.util.Platform;
61 import jalview.ws.sifts.SiftsSettings;
64 * Stores and retrieves Jalview Application Properties Lists and fields within
65 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
66 * are alternative values for a tag. <br>
68 * Current properties include:
71 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
72 * logging level for axis (used for web services) <br>
74 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
75 * the logging level for castor (used for serialization) <br>
77 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
79 * <li>SCREEN_WIDTH</li>
80 * <li>SCREEN_HEIGHT</li>
81 * <li>SCREEN_Y=285</li>
82 * <li>SCREEN_X=371</li>
83 * <li>SHOW_FULLSCREEN boolean</li>
84 * <li>FONT_NAME java font name for alignment text display</li>
85 * <li>FONT_SIZE size of displayed alignment text</li>
86 * <li>FONT_STYLE style of font displayed (sequence labels are always
88 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
89 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
90 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
91 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
92 * <li>SHOW_IDENTITY show percentage identity annotation</li>
93 * <li>SHOW_QUALITY show alignment quality annotation</li>
94 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
95 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
96 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
97 * LABEL_AND_SEQUENCE</li>
98 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
99 * sequence annotations</li>
100 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
101 * annotation row</li>
102 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
103 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
104 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
105 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
106 * <li>VERSION the version of the jalview build</li>
107 * <li>BUILD_DATE date of this build</li>
108 * <li>LATEST_VERSION the latest jalview version advertised on the
109 * www.jalview.org</li>
110 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
112 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
113 * suffix to file</li>
114 * <li>RECENT_URL list of recently retrieved URLs</li>
115 * <li>RECENT_FILE list of recently opened files</li>
116 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
117 * <li>PROXY_SERVER the proxy</li>
118 * <li>PROXY_PORT</li>
119 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
121 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
123 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
124 * collecting usage statistics</li>
125 * <li>SHOW_OVERVIEW boolean for overview window display</li>
126 * <li>ANTI_ALIAS boolean for smooth fonts</li>
127 * <li>RIGHT_ALIGN_IDS boolean</li>
128 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
129 * <li>PAD_GAPS boolean</li>
130 * <li>ID_ITALICS boolean</li>
131 * <li>SHOW_JV_SUFFIX</li>
132 * <li>WRAP_ALIGNMENT</li>
133 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
135 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
136 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
138 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
140 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
141 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
142 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
143 * jalview.utils.GroupURLLink for more info</li>
144 * <li>DEFAULT_BROWSER for unix</li>
145 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
147 * <li>VERSION_CHECK (true) check for the latest release version from
148 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
149 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
151 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
153 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
154 * displayed as '.'</li>
155 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
156 * order of a newly displayed tree</li>
157 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
158 * sequence ID strings before attempting retrieval from any datasource</li>
159 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
161 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
162 * in the alignment.</li>
163 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
165 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
167 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
168 * logo normalised to row height rather than histogram height.</li>
169 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
170 * respond to selections made in other alignments containing the same sequences.
172 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
173 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
174 * warning dialog box is displayed.</li>
175 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
176 * when shading by annotation</li>
177 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
178 * when shading by annotation</li>
179 * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
180 * requests to be redirected to a mirror of http://www.jalview.org</li>
181 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
182 * alignment figure to accommodate even the longest sequence ID or annotation
184 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
185 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
186 * will override this).</li>
187 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
189 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
190 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
192 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
194 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
196 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
197 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
201 * Deprecated settings:
204 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
205 * startup (JWS1 services only)</li>
206 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
207 * (JWS1 services only)</li>
208 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
209 * services in the desktop GUI</li>
210 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
211 * panel in web service preferences</li>
215 * @version $Revision$
220 * property giving log4j level for CASTOR loggers
222 public static final String CASTORLOGLEVEL = "logs.Castor.level";
225 * property giving log4j level for AXIS loggers
227 public static final String AXISLOGLEVEL = "logs.Axis.level";
230 * property giving log4j level for Jalview Log
232 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
237 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
238 .getProperty("user.home") + File.separatorChar
239 + ".sifts_downloads" + File.separatorChar;
241 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
243 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
246 * Identifiers.org download settings
248 private static final String ID_ORG_FILE = System.getProperty("user.home")
249 + File.separatorChar + ".identifiers.org.ids.json";
252 * Allowed values are PDB or mmCIF
254 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
257 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
261 * a date formatter using a fixed (rather than the user's) locale;
262 * this ensures that date properties can be written and re-read successfully
263 * even if the user changes their locale setting
265 private static final DateFormat date_format = SimpleDateFormat
266 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
267 SimpleDateFormat.MEDIUM, Locale.UK);
270 * Initialises the Jalview Application Log
272 public static Logger log;
274 // save the proxy properties set at startup
275 public final static String[] startupProxyProperties = {
276 System.getProperty("http.proxyHost"),
277 System.getProperty("http.proxyPort"),
278 System.getProperty("https.proxyHost"),
279 System.getProperty("https.proxyPort") };
281 /** Jalview Properties */
282 public static Properties applicationProperties = new Properties()
284 // override results in properties output in alphabetical order
286 public synchronized Enumeration<Object> keys()
288 return Collections.enumeration(new TreeSet<>(super.keySet()));
292 /** Default file is ~/.jalview_properties */
293 static String propertiesFile;
295 private static boolean propsAreReadOnly = Platform.isJS();
297 private final static String JS_PROPERTY_PREFIX = "jalview_";
299 public static void initLogger()
307 // TODO: redirect stdout and stderr here in order to grab the output of
310 ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
312 ap.setName("JalviewLogger");
313 org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
315 Logger laxis = Logger.getLogger("org.apache.axis");
316 Logger lcastor = Logger.getLogger("org.exolab.castor");
317 jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
319 laxis.setLevel(Level.toLevel(
320 Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
321 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
322 Level.INFO.toString())));
323 lcastor = Logger.getLogger("org.exolab.castor.xml");
324 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
325 Level.INFO.toString())));
326 // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
327 // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
328 // Level.INFO.toString())));
329 // we shouldn't need to do this
330 org.apache.log4j.Logger.getRootLogger()
331 .setLevel(org.apache.log4j.Level.INFO);
333 jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
334 .getDefault("logs.Jalview.level", Level.INFO.toString())));
335 // laxis.addAppender(ap);
336 // lcastor.addAppender(ap);
337 // jalview.bin.Cache.log.addAppender(ap);
338 // Tell the user that debug is enabled
339 jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
340 } catch (Exception ex)
342 System.err.println("Problems initializing the log4j system\n");
343 ex.printStackTrace(System.err);
348 * Loads properties from the given properties file. Any existing properties
351 public static void loadProperties(String propsFile)
353 propertiesFile = propsFile;
354 if (propsFile == null && !propsAreReadOnly)
356 propertiesFile = System.getProperty("user.home") + File.separatorChar
357 + ".jalview_properties";
361 // don't corrupt the file we've been given.
362 propsAreReadOnly = true;
365 if (propertiesFile == null)
367 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
368 applicationProperties);
377 fis = new URL(propertiesFile).openStream();
379 "Loading jalview properties from : " + propertiesFile);
381 "Disabling Jalview writing to user's local properties file.");
382 propsAreReadOnly = true;
384 } catch (Exception ex)
390 fis = new FileInputStream(propertiesFile);
392 applicationProperties.clear();
393 applicationProperties.load(fis);
395 // remove any old build properties
397 deleteBuildProperties();
399 } catch (Exception ex)
401 System.out.println("Error reading properties file: " + ex);
405 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
406 if (getDefault("USE_PROXY", false))
408 String proxyServer = getDefault("PROXY_SERVER", ""),
409 proxyPort = getDefault("PROXY_PORT", "8080");
413 // PROXY TYPE settings (now three options "none", "false", "true", but using
414 // backward compatible strings)
415 String proxyType = getDefault("USE_PROXY", "false");
416 // default to upgrading old settings
420 setProxyProperties(null, null, null, null);
422 case "false": // use system settings
423 resetProxyProperties();
425 case "true": // use specified proxy settings
426 String httpHost = getDefault("PROXY_SERVER", "");
427 String httpPort = getDefault("PROXY_PORT", "8080");
428 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
429 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
430 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort);
433 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
435 if (Cache.log == null)
437 System.out.println(message);
441 Cache.log.warn(message);
445 // LOAD THE AUTHORS FROM THE authors.props file
446 String authorDetails = resolveResourceURLFor("/authors.props");
450 if (authorDetails != null)
452 URL localJarFileURL = new URL(authorDetails);
453 InputStream in = localJarFileURL.openStream();
454 applicationProperties.load(in);
457 } catch (Exception ex)
459 System.out.println("Error reading author details: " + ex);
460 authorDetails = null;
462 if (authorDetails == null)
464 applicationProperties.remove("AUTHORS");
465 applicationProperties.remove("AUTHORFNAMES");
466 applicationProperties.remove("YEAR");
469 loadBuildProperties(false);
472 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
474 SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
475 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
477 SiftsSettings.setFailSafePIDThreshold(
478 jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
479 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
481 SiftsSettings.setCacheThresholdInDays(
482 jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
483 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
485 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
486 "http://www.jalview.org/services/identifiers"));
487 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
489 StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
490 .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
491 StructureImportSettings
492 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
493 // StructureImportSettings
494 // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
495 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
497 String jnlpVersion = System.getProperty("jalview.version");
499 // jnlpVersion will be null if a latest version check for the channel needs
501 // Dont do this check if running in headless mode
503 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
504 && (System.getProperty("java.awt.headless") == null || System
505 .getProperty("java.awt.headless").equals("false")))
508 class VersionChecker extends Thread
513 String orgtimeout = System
514 .getProperty("sun.net.client.defaultConnectTimeout");
515 if (orgtimeout == null)
518 System.out.println("# INFO: Setting default net timeout to "
519 + orgtimeout + " seconds.");
521 String remoteVersion = null;
524 System.setProperty("sun.net.client.defaultConnectTimeout",
526 java.net.URL url = new java.net.URL(Cache
527 .getDefault("www.jalview.org", "http://www.jalview.org")
528 + "/webstart/jalview.jnlp");
529 BufferedReader in = new BufferedReader(
530 new InputStreamReader(url.openStream()));
532 while ((line = in.readLine()) != null)
534 if (line.indexOf("jalview.version") == -1)
539 line = line.substring(line.indexOf("value=") + 7);
540 line = line.substring(0, line.lastIndexOf("\""));
541 remoteVersion = line;
544 } catch (Exception ex)
547 "Non-fatal exception when checking version at www.jalview.org :");
548 System.out.println(ex);
549 remoteVersion = getProperty("VERSION");
551 System.setProperty("sun.net.client.defaultConnectTimeout",
554 setProperty("LATEST_VERSION", remoteVersion);
558 VersionChecker vc = new VersionChecker();
563 if (jnlpVersion != null)
565 setProperty("LATEST_VERSION", jnlpVersion);
569 applicationProperties.remove("LATEST_VERSION");
573 // LOAD USERDEFINED COLOURS
574 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
575 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
580 * construct a resource URL for the given absolute resource pathname
582 * @param resourcePath
585 private static String resolveResourceURLFor(String resourcePath)
588 if (Platform.isJS() || !Cache.class.getProtectionDomain()
589 .getCodeSource().getLocation().toString().endsWith(".jar"))
593 url = Cache.class.getResource(resourcePath).toString();
594 } catch (Exception ex)
596 System.err.println("Failed to resolve resource " + resourcePath
597 + ": " + ex.getMessage());
602 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
603 .getLocation().toString().concat("!" + resourcePath));
608 public static void loadBuildProperties(boolean reportVersion)
610 String codeInstallation = getProperty("INSTALLATION");
611 boolean printVersion = codeInstallation == null;
614 * read build properties - from the Jalview jar for a Java distribution,
615 * or from codebase file in test or JalviewJS context
619 String buildDetails = resolveResourceURLFor("/.build_properties");
620 URL localJarFileURL = new URL(buildDetails);
621 InputStream in = localJarFileURL.openStream();
622 applicationProperties.load(in);
624 } catch (Exception ex)
626 System.out.println("Error reading build details: " + ex);
627 applicationProperties.remove("VERSION");
629 String codeVersion = getProperty("VERSION");
630 codeInstallation = getProperty("INSTALLATION");
632 if (codeVersion == null)
634 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
635 codeVersion = "Test";
636 codeInstallation = "";
640 codeInstallation = " (" + codeInstallation + ")";
642 setProperty("VERSION", codeVersion);
643 new BuildDetails(codeVersion, null, codeInstallation);
644 if (printVersion && reportVersion)
647 "Jalview Version: " + codeVersion + codeInstallation);
651 private static void deleteBuildProperties()
653 applicationProperties.remove("LATEST_VERSION");
654 applicationProperties.remove("VERSION");
655 applicationProperties.remove("AUTHORS");
656 applicationProperties.remove("AUTHORFNAMES");
657 applicationProperties.remove("YEAR");
658 applicationProperties.remove("BUILD_DATE");
659 applicationProperties.remove("INSTALLATION");
663 * Gets Jalview application property of given key. Returns null if key not
669 * @return Property value
671 public static String getProperty(String key)
673 String prop = applicationProperties.getProperty(key);
674 if (prop == null && Platform.isJS())
676 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
677 + "_" + JS_PROPERTY_PREFIX + key);
683 * These methods are used when checking if the saved preference is different
684 * to the default setting
687 public static boolean getDefault(String property, boolean def)
689 String string = getProperty(property);
692 def = Boolean.valueOf(string).booleanValue();
698 public static int getDefault(String property, int def)
700 String string = getProperty(property);
705 def = Integer.parseInt(string);
706 } catch (NumberFormatException e)
708 System.out.println("Error parsing int property '" + property
709 + "' with value '" + string + "'");
717 * Answers the value of the given property, or the supplied default value if
718 * the property is not set
720 public static String getDefault(String property, String def)
722 String value = getProperty(property);
723 return value == null ? def : value;
727 * Stores property in the file "HOME_DIR/.jalview_properties"
732 * String value of property
734 * @return previous value of property (or null)
736 public static Object setProperty(String key, String obj)
738 Object oldValue = null;
741 oldValue = applicationProperties.setProperty(key, obj);
742 if (propertiesFile != null && !propsAreReadOnly)
744 FileOutputStream out = new FileOutputStream(propertiesFile);
745 applicationProperties.store(out, "---JalviewX Properties File---");
748 } catch (Exception ex)
751 "Error setting property: " + key + " " + obj + "\n" + ex);
757 * remove the specified property from the jalview properties file
761 public static void removeProperty(String string)
763 applicationProperties.remove(string);
768 * save the properties to the jalview properties path
770 public static void saveProperties()
772 if (!propsAreReadOnly)
776 FileOutputStream out = new FileOutputStream(propertiesFile);
777 applicationProperties.store(out, "---JalviewX Properties File---");
779 } catch (Exception ex)
781 System.out.println("Error saving properties: " + ex);
787 * internal vamsas class discovery state
789 private static int vamsasJarsArePresent = -1;
792 * Searches for vamsas client classes on class path.
794 * @return true if vamsas client is present on classpath
796 public static boolean vamsasJarsPresent()
798 if (vamsasJarsArePresent == -1)
802 if (jalview.jbgui.GDesktop.class.getClassLoader()
803 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
805 jalview.bin.Cache.log.debug(
806 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
807 vamsasJarsArePresent = 1;
808 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
809 lvclient.setLevel(Level.toLevel(Cache
810 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
812 lvclient.addAppender(log.getAppender("JalviewLogger"));
813 // Tell the user that debug is enabled
814 lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
816 } catch (Exception e)
818 vamsasJarsArePresent = 0;
819 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
822 return (vamsasJarsArePresent > 0);
826 * internal vamsas class discovery state
828 private static int groovyJarsArePresent = -1;
831 * Searches for vamsas client classes on class path.
833 * @return true if vamsas client is present on classpath
835 public static boolean groovyJarsPresent()
837 if (groovyJarsArePresent == -1)
841 if (Cache.class.getClassLoader()
842 .loadClass("groovy.lang.GroovyObject") != null)
844 jalview.bin.Cache.log.debug(
845 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
846 groovyJarsArePresent = 1;
847 Logger lgclient = Logger.getLogger("groovy");
848 lgclient.setLevel(Level.toLevel(Cache
849 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
851 lgclient.addAppender(log.getAppender("JalviewLogger"));
852 // Tell the user that debug is enabled
853 lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
857 groovyJarsArePresent = 0;
858 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
859 } catch (Exception e)
861 groovyJarsArePresent = 0;
862 jalview.bin.Cache.log.debug("Groovy Classes are not present");
865 return (groovyJarsArePresent > 0);
869 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
872 protected static Object tracker = null;
874 protected static Class trackerfocus = null;
876 protected static Class jgoogleanalyticstracker = null;
879 * Initialise the google tracker if it is not done already.
881 public static void initGoogleTracker()
885 if (jgoogleanalyticstracker == null)
887 // try to get the tracker class
890 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
891 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
892 trackerfocus = Cache.class.getClassLoader()
893 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
894 } catch (Exception e)
897 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
899 jgoogleanalyticstracker = null;
904 // now initialise tracker
905 Exception re = null, ex = null;
907 String vrs = "No Version Accessible";
910 // Google analytics tracking code for Library Finder
911 tracker = jgoogleanalyticstracker
912 .getConstructor(new Class[]
913 { String.class, String.class, String.class })
914 .newInstance(new Object[]
916 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
917 + jalview.bin.Cache.getDefault("BUILD_DATE",
920 jgoogleanalyticstracker
921 .getMethod("trackAsynchronously", new Class[]
923 .invoke(tracker, new Object[]
924 { trackerfocus.getConstructor(new Class[] { String.class })
925 .newInstance(new Object[]
926 { "Application Started." }) });
927 } catch (RuntimeException e)
930 } catch (Exception e)
937 if (re != null || ex != null || err != null)
943 log.debug("Caught runtime exception in googletracker init:",
949 "Failed to initialise GoogleTracker for Jalview Desktop with version "
956 "Whilst initing GoogleTracker for Jalview Desktop version "
966 "Debug: Caught runtime exception in googletracker init:"
968 re.printStackTrace();
973 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
975 ex.printStackTrace();
981 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
983 err.printStackTrace();
989 log.debug("Successfully initialised tracker.");
995 * get the user's default colour if available
1001 public static Color getDefaultColour(String property, Color defcolour)
1003 String colprop = getProperty(property);
1004 if (colprop == null)
1008 Color col = ColorUtils.parseColourString(colprop);
1011 log.warn("Couldn't parse '" + colprop + "' as a colour for "
1014 return (col == null) ? defcolour : col;
1018 * store a colour as a Jalview user default property
1023 public static void setColourProperty(String property, Color colour)
1025 setProperty(property, jalview.util.Format.getHexString(colour));
1029 * Stores a formatted date in a jalview property, using a fixed locale.
1031 * @param propertyName
1033 * @return the formatted date string
1035 public static String setDateProperty(String propertyName, Date date)
1037 String formatted = date_format.format(date);
1038 setProperty(propertyName, formatted);
1043 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1044 * format) and returns as a Date, or null if parsing fails
1046 * @param propertyName
1050 public static Date getDateProperty(String propertyName)
1052 String val = getProperty(propertyName);
1057 return date_format.parse(val);
1058 } catch (Exception ex)
1060 System.err.println("Invalid or corrupt date in property '"
1061 + propertyName + "' : value was '" + val + "'");
1068 * get and parse a property as an integer. send any parsing problems to
1072 * @return null or Integer
1074 public static Integer getIntegerProperty(String property)
1076 String val = getProperty(property);
1077 if (val != null && (val = val.trim()).length() > 0)
1081 return Integer.valueOf(val);
1082 } catch (NumberFormatException x)
1084 System.err.println("Invalid integer in property '" + property
1085 + "' (value was '" + val + "')");
1092 * Set the specified value, or remove it if null or empty. Does not save the
1098 public static void setOrRemove(String propName, String value)
1100 if (propName == null)
1104 if (value == null || value.trim().length() < 1)
1106 Cache.applicationProperties.remove(propName);
1110 Cache.applicationProperties.setProperty(propName, value);
1115 * Loads in user colour schemes from files.
1118 * a '|'-delimited list of file paths
1120 public static void initUserColourSchemes(String files)
1122 if (files == null || files.length() == 0)
1127 // In case colours can't be loaded, we'll remove them
1128 // from the default list here.
1129 StringBuffer coloursFound = new StringBuffer();
1130 StringTokenizer st = new StringTokenizer(files, "|");
1131 while (st.hasMoreElements())
1133 String file = st.nextToken();
1136 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1139 if (coloursFound.length() > 0)
1141 coloursFound.append("|");
1143 coloursFound.append(file);
1144 ColourSchemes.getInstance().registerColourScheme(ucs);
1146 } catch (Exception ex)
1148 System.out.println("Error loading User ColourFile\n" + ex);
1151 if (!files.equals(coloursFound.toString()))
1153 if (coloursFound.toString().length() > 1)
1155 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1156 coloursFound.toString());
1160 applicationProperties
1161 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1167 * Initial logging information helper for various versions output
1171 * @param defaultValue
1173 private static void appendIfNotNull(StringBuilder sb, String prefix,
1174 String value, String suffix, String defaultValue)
1176 if (value == null && defaultValue == null)
1180 String line = prefix + (value != null ? value : defaultValue) + suffix;
1186 * @return Jalview version, build details and JVM platform version for console
1188 public static String getVersionDetailsForConsole()
1190 StringBuilder sb = new StringBuilder();
1191 sb.append("Jalview Version: ");
1192 sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1194 sb.append("Jalview Installation: ");
1195 sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1197 sb.append("Build Date: ");
1198 sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1200 sb.append("Java version: ");
1201 sb.append(System.getProperty("java.version"));
1203 sb.append(System.getProperty("os.arch"));
1205 sb.append(System.getProperty("os.name"));
1207 sb.append(System.getProperty("os.version"));
1209 appendIfNotNull(sb, "Install4j version: ",
1210 System.getProperty("sys.install4jVersion"), "\n", null);
1211 appendIfNotNull(sb, "Install4j template version: ",
1212 System.getProperty("installer_template_version"), "\n", null);
1213 appendIfNotNull(sb, "Launcher version: ",
1214 System.getProperty("launcher_version"), "\n", null);
1215 LookAndFeel laf = UIManager.getLookAndFeel();
1216 String lafName = laf == null ? "Not obtained" : laf.getName();
1217 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1218 sb.append("LookAndFeel: ");
1221 sb.append(lafClass);
1223 // Not displayed in release version ( determined by possible version number
1224 // regex 9[9.]*9[.-_a9]* )
1225 if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1226 jalview.bin.Cache.getDefault("VERSION", "TEST")))
1228 appendIfNotNull(sb, "Getdown appdir: ",
1229 System.getProperty("getdownappdir"), "\n", null);
1230 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1233 return sb.toString();
1238 * @return build details as reported in splashscreen
1240 public static String getBuildDetailsForSplash()
1242 // consider returning more human friendly info
1243 // eg 'built from Source' or update channel
1244 return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1247 public static String getStackTraceString(Throwable t)
1249 StringWriter sw = new StringWriter();
1250 PrintWriter pw = new PrintWriter(sw);
1251 t.printStackTrace(pw);
1252 return sw.toString();
1255 // proxy properties methods
1256 public static void resetProxyProperties()
1258 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1259 startupProxyProperties[2], startupProxyProperties[3]);
1260 StringBuilder sb = new StringBuilder();
1261 sb.append("Setting proxy properties to: http.proxyHost=")
1262 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1263 .append(startupProxyProperties[1]).append(", https.proxyHost=")
1264 .append(startupProxyProperties[2]).append(", https.proxyPort=")
1265 .append(startupProxyProperties[3]);
1266 if (Cache.log == null)
1268 System.err.println(sb.toString());
1272 Cache.log.debug(sb.toString());
1276 public static void setProxyProperties(String host, String port)
1278 setProxyProperties(host, port, host, port);
1281 public static void setProxyProperties(String httpHost, String httpPort,
1282 String httpsHost, String httpsPort)
1284 // cannot set property to null -- use clearProperty instead
1287 if (httpHost == null)
1289 System.clearProperty("http.proxyHost");
1293 System.setProperty("http.proxyHost", httpHost);
1297 if (httpPort == null)
1299 System.clearProperty("http.proxyPort");
1303 System.setProperty("http.proxyPort", httpPort);
1307 if (httpsHost == null)
1309 System.clearProperty("https.proxyHost");
1313 System.setProperty("https.proxyHost", httpsHost);
1317 if (httpsPort == null)
1319 System.clearProperty("https.proxyPort");
1323 System.setProperty("https.proxyPort", httpsPort);