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.awt.Dimension;
25 import java.io.BufferedReader;
27 import java.io.FileInputStream;
28 import java.io.FileOutputStream;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
32 import java.text.DateFormat;
33 import java.text.SimpleDateFormat;
34 import java.util.Collections;
35 import java.util.Date;
36 import java.util.Enumeration;
37 import java.util.Locale;
38 import java.util.Properties;
39 import java.util.StringTokenizer;
40 import java.util.TreeSet;
42 import org.apache.log4j.ConsoleAppender;
43 import org.apache.log4j.Level;
44 import org.apache.log4j.Logger;
45 import org.apache.log4j.SimpleLayout;
47 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
48 import jalview.datamodel.PDBEntry;
49 import jalview.gui.Preferences;
50 import jalview.schemes.ColourSchemeLoader;
51 import jalview.schemes.ColourSchemes;
52 import jalview.schemes.UserColourScheme;
53 import jalview.structure.StructureImportSettings;
54 import jalview.urls.IdOrgSettings;
55 import jalview.util.ColorUtils;
56 import jalview.util.Platform;
57 import jalview.ws.sifts.SiftsSettings;
60 * Stores and retrieves Jalview Application Properties Lists and fields within
61 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
62 * are alternative values for a tag. <br>
64 * Current properties include:
67 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
68 * logging level for axis (used for web services) <br>
70 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
71 * the logging level for castor (used for serialization) <br>
73 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
75 * <li>SCREEN_WIDTH</li>
76 * <li>SCREEN_HEIGHT</li>
77 * <li>SCREEN_Y=285</li>
78 * <li>SCREEN_X=371</li>
79 * <li>SHOW_FULLSCREEN boolean</li>
80 * <li>FONT_NAME java font name for alignment text display</li>
81 * <li>FONT_SIZE size of displayed alignment text</li>
82 * <li>FONT_STYLE style of font displayed (sequence labels are always
84 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
85 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
86 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
87 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
88 * <li>SHOW_IDENTITY show percentage identity annotation</li>
89 * <li>SHOW_QUALITY show alignment quality annotation</li>
90 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
91 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
92 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
93 * LABEL_AND_SEQUENCE</li>
94 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
95 * sequence annotations</li>
96 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
98 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
99 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
100 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
101 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
102 * <li>VERSION the version of the jalview build</li>
103 * <li>BUILD_DATE date of this build</li>
104 * <li>LATEST_VERSION the latest jalview version advertised on the
105 * www.jalview.org</li>
106 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
108 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
109 * suffix to file</li>
110 * <li>RECENT_URL list of recently retrieved URLs</li>
111 * <li>RECENT_FILE list of recently opened files</li>
112 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
113 * <li>PROXY_SERVER the proxy</li>
114 * <li>PROXY_PORT</li>
115 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
117 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
119 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
120 * collecting usage statistics</li>
121 * <li>SHOW_OVERVIEW boolean for overview window display</li>
122 * <li>ANTI_ALIAS boolean for smooth fonts</li>
123 * <li>RIGHT_ALIGN_IDS boolean</li>
124 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
125 * <li>PAD_GAPS boolean</li>
126 * <li>ID_ITALICS boolean</li>
127 * <li>SHOW_JV_SUFFIX</li>
128 * <li>WRAP_ALIGNMENT</li>
129 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
131 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
132 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
134 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
136 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
137 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
138 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
139 * jalview.utils.GroupURLLink for more info</li>
140 * <li>DEFAULT_BROWSER for unix</li>
141 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
143 * <li>VERSION_CHECK (true) check for the latest release version from
144 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
145 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
147 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
149 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
150 * displayed as '.'</li>
151 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
152 * order of a newly displayed tree</li>
153 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
154 * sequence ID strings before attempting retrieval from any datasource</li>
155 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
157 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
158 * in the alignment.</li>
159 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
161 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
163 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
164 * logo normalised to row height rather than histogram height.</li>
165 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
166 * respond to selections made in other alignments containing the same sequences.
168 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
169 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
170 * warning dialog box is displayed.</li>
171 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
172 * when shading by annotation</li>
173 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
174 * when shading by annotation</li>
175 * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
176 * requests to be redirected to a mirror of http://www.jalview.org</li>
177 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
178 * alignment figure to accommodate even the longest sequence ID or annotation
180 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
181 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
182 * will override this).</li>
183 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
185 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
186 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
188 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
190 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
192 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
193 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
197 * Deprecated settings:
200 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
201 * startup (JWS1 services only)</li>
202 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
203 * (JWS1 services only)</li>
204 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
205 * services in the desktop GUI</li>
206 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
207 * panel in web service preferences</li>
211 * @version $Revision$
213 public class Cache implements ApplicationSingletonI
222 * In Java, this will be a static field instance, which will be
223 * application-specific; in JavaScript it will be an applet-specific instance
224 * tied to the applet's ThreadGroup.
228 public static Cache getInstance()
230 return (Cache) ApplicationSingletonProvider.getInstance(Cache.class);
234 * property giving log4j level for CASTOR loggers
236 public static final String CASTORLOGLEVEL = "logs.Castor.level";
239 * property giving log4j level for AXIS loggers
241 public static final String AXISLOGLEVEL = "logs.Axis.level";
244 * property giving log4j level for Jalview Log
246 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
251 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
252 .getProperty("user.home") + File.separatorChar
253 + ".sifts_downloads" + File.separatorChar;
255 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
257 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
260 * Identifiers.org download settings
262 private static final String ID_ORG_FILE = System.getProperty("user.home")
263 + File.separatorChar + ".identifiers.org.ids.json";
266 * Allowed values are PDB or mmCIF
268 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
271 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
275 * a date formatter using a fixed (rather than the user's) locale;
276 * this ensures that date properties can be written and re-read successfully
277 * even if the user changes their locale setting
279 private static final DateFormat date_format = SimpleDateFormat
280 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
281 SimpleDateFormat.MEDIUM, Locale.UK);
284 * Initialises the Jalview Application Log
286 public static Logger log;
288 /** Jalview Properties */
289 // BH 2019.05.08 was static
290 @SuppressWarnings("serial")
291 public Properties applicationProperties = new Properties()
293 // override results in properties output in alphabetical order
295 public synchronized Enumeration<Object> keys()
297 return Collections.enumeration(new TreeSet<>(super.keySet()));
301 /** Default file is ~/.jalview_properties */
302 // BH 2020 private, not static
303 private String propertiesFile;
305 private static boolean propsAreReadOnly = Platform.isJS();
307 private final static String JS_PROPERTY_PREFIX = "jalview_";
309 public static void initLogger()
317 // TODO: redirect stdout and stderr here in order to grab the output of
320 ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
322 ap.setName("JalviewLogger");
323 org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
325 Logger laxis = Logger.getLogger("org.apache.axis");
326 Logger lcastor = Logger.getLogger("org.exolab.castor");
327 jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
329 laxis.setLevel(Level.toLevel(
330 Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
331 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
332 Level.INFO.toString())));
333 lcastor = Logger.getLogger("org.exolab.castor.xml");
334 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
335 Level.INFO.toString())));
336 // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
337 // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
338 // Level.INFO.toString())));
339 jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
340 .getDefault("logs.Jalview.level", Level.INFO.toString())));
341 // laxis.addAppender(ap);
342 // lcastor.addAppender(ap);
343 // jalview.bin.Cache.log.addAppender(ap);
344 // Tell the user that debug is enabled
345 jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
346 } catch (Exception ex)
348 System.err.println("Problems initializing the log4j system\n");
349 ex.printStackTrace(System.err);
354 * Loads properties from the given properties file. Any existing properties
357 public static void loadProperties(String propsFile)
359 getInstance().loadPropertiesImpl(propsFile);
362 private void loadPropertiesImpl(String propsFile)
364 propertiesFile = propsFile;
365 if (propsFile == null && !propsAreReadOnly)
367 propertiesFile = System.getProperty("user.home") + File.separatorChar
368 + ".jalview_properties";
372 // don't corrupt the file we've been given.
373 propsAreReadOnly = true;
376 if (propertiesFile == null)
378 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
379 applicationProperties);
388 fis = new java.net.URL(propertiesFile).openStream();
390 "Loading jalview properties from : " + propertiesFile);
392 "Disabling Jalview writing to user's local properties file.");
393 propsAreReadOnly = true;
395 } catch (Exception ex)
401 fis = new FileInputStream(propertiesFile);
403 applicationProperties.clear();
404 applicationProperties.load(fis);
406 // remove any old build properties
408 deleteBuildProperties();
410 } catch (Exception ex)
412 System.out.println("Error reading properties file: " + ex);
415 if (getDefault("USE_PROXY", false))
417 String proxyServer = getDefault("PROXY_SERVER", ""),
418 proxyPort = getDefault("PROXY_PORT", "8080");
420 System.out.println("Using proxyServer: " + proxyServer
421 + " proxyPort: " + proxyPort);
423 System.setProperty("http.proxyHost", proxyServer);
424 System.setProperty("http.proxyPort", proxyPort);
427 // LOAD THE AUTHORS FROM THE authors.props file
428 String authorDetails = (Platform.isJS() ? null
429 : resolveResourceURLFor("/authors.props"));
433 if (authorDetails != null)
435 URL localJarFileURL = new URL(authorDetails);
436 InputStream in = localJarFileURL.openStream();
437 applicationProperties.load(in);
440 } catch (Exception ex)
442 System.out.println("Error reading author details: " + ex);
443 authorDetails = null;
445 if (authorDetails == null)
447 applicationProperties.remove("AUTHORS");
448 applicationProperties.remove("AUTHORFNAMES");
449 applicationProperties.remove("YEAR");
452 loadBuildProperties(false);
455 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
457 SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
458 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
460 SiftsSettings.setFailSafePIDThreshold(
461 jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
462 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
464 SiftsSettings.setCacheThresholdInDays(
465 jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
466 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
468 IdOrgSettings.setUrl(getDefault(Preferences.ID_ORG_HOSTURL,
469 "http://www.jalview.org/services/identifiers"));
470 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
472 StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
473 .getDefault(Preferences.PDB_DOWNLOAD_FORMAT, PDB_DOWNLOAD_FORMAT));
474 StructureImportSettings
475 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
476 // StructureImportSettings
477 // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
478 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
480 String jnlpVersion = System.getProperty("jalview.version");
482 // jnlpVersion will be null if a latest version check for the channel needs to
484 // Dont do this check if running in headless mode
486 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
487 && (System.getProperty("java.awt.headless") == null || System
488 .getProperty("java.awt.headless").equals("false")))
495 String orgtimeout = System
496 .getProperty("sun.net.client.defaultConnectTimeout");
497 if (orgtimeout == null)
500 System.out.println("# INFO: Setting default net timeout to "
501 + orgtimeout + " seconds.");
503 String remoteVersion = null;
506 System.setProperty("sun.net.client.defaultConnectTimeout",
508 java.net.URL url = new java.net.URL(Cache
509 .getDefault("www.jalview.org", "http://www.jalview.org")
510 + "/webstart/jalview.jnlp");
511 BufferedReader in = new BufferedReader(
512 new InputStreamReader(url.openStream()));
514 while ((line = in.readLine()) != null)
516 if (line.indexOf("jalview.version") == -1)
521 line = line.substring(line.indexOf("value=") + 7);
522 line = line.substring(0, line.lastIndexOf("\""));
523 remoteVersion = line;
526 } catch (Exception ex)
529 "Non-fatal exception when checking version at www.jalview.org :");
530 System.out.println(ex);
531 remoteVersion = getProperty("VERSION");
533 System.setProperty("sun.net.client.defaultConnectTimeout",
536 setProperty("LATEST_VERSION", remoteVersion);
542 if (jnlpVersion != null)
544 setProperty("LATEST_VERSION", jnlpVersion);
548 applicationProperties.remove("LATEST_VERSION");
552 // LOAD USERDEFINED COLOURS
553 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
554 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
559 * construct a resource URL for the given absolute resource pathname
561 * @param resourcePath
564 private static String resolveResourceURLFor(String resourcePath)
567 if (Platform.isJS() || !Cache.class.getProtectionDomain()
568 .getCodeSource().getLocation().toString().endsWith(".jar"))
572 url = Cache.class.getResource(resourcePath).toString();
573 } catch (Exception ex)
575 System.err.println("Failed to resolve resource " + resourcePath + ": "
581 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
582 .getLocation().toString().concat("!" + resourcePath));
587 public static void loadBuildProperties(boolean reportVersion)
589 String codeInstallation = getProperty("INSTALLATION");
590 boolean printVersion = codeInstallation == null;
593 * read build properties - from the Jalview jar for a Java distribution,
594 * or from codebase file in test or JalviewJS context
598 String buildDetails = resolveResourceURLFor("/.build_properties");
599 URL localJarFileURL = new URL(buildDetails);
600 InputStream in = localJarFileURL.openStream();
601 getInstance().applicationProperties.load(in);
603 } catch (Exception ex)
605 System.out.println("Error reading build details: " + ex);
606 getInstance().applicationProperties.remove("VERSION");
608 String codeVersion = getProperty("VERSION");
609 codeInstallation = getProperty("INSTALLATION");
611 if (codeVersion == null)
613 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
614 codeVersion = "Test";
615 codeInstallation = "";
619 codeInstallation = " (" + codeInstallation + ")";
621 setProperty("VERSION", codeVersion);
622 new BuildDetails(codeVersion, null, codeInstallation);
623 if (printVersion && reportVersion)
626 .println("Jalview Version: " + codeVersion + codeInstallation);
630 // BH 2020 was static
631 private void deleteBuildProperties()
633 applicationProperties.remove("LATEST_VERSION");
634 applicationProperties.remove("VERSION");
635 applicationProperties.remove("AUTHORS");
636 applicationProperties.remove("AUTHORFNAMES");
637 applicationProperties.remove("YEAR");
638 applicationProperties.remove("BUILD_DATE");
639 applicationProperties.remove("INSTALLATION");
643 * Gets Jalview application property of given key. Returns null if key not
649 * @return Property value
651 public static String getProperty(String key)
653 return getInstance().applicationProperties.getProperty(key);
655 // old, original idea:
656 // String prop = applicationProperties.getProperty(key);
657 // if (prop == null && Platform.isJS())
659 // prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
660 // + "_" + JS_PROPERTY_PREFIX + key);
667 //These methods are used when checking if the saved preference is different
668 // to the default setting
671 * Returns the boolean property value for the given property name. If the
672 * value is absent then the default value is returned instead.
678 public static boolean getDefault(String property, boolean def)
680 String string = getProperty(property);
681 // BH simplification only
682 return string == null ? def : Boolean.parseBoolean(string);
686 * Returns the integer property value for the given property name. If the
687 * value is absent, or malformed (not an integer), then the default value is
694 public static int getDefault(String property, int def)
696 String string = getProperty(property);
701 // BH simplification only
703 return Integer.parseInt(string);
704 } catch (NumberFormatException e)
706 System.out.println("Error parsing int property '" + property
707 + "' with value '" + string + "'");
715 * Returns the value of the given property, or the supplied default value if
716 * the property is not set
722 public static String getDefault(String property, String def)
724 String value = getProperty(property);
725 return value == null ? def : value;
729 * Stores property in the file "HOME_DIR/.jalview_properties"
734 * String value of property
736 * @return previous value of property (or null)
738 public static Object setProperty(String key, String obj)
740 return getInstance().setPropertyImpl(key, obj, true);
744 * Sets a property value for the running application, without saving it to the
747 * Used extensively in AppletParams and Preferences.ok_actionPerformed
753 public static void setPropertyNoSave(String key, String obj)
755 getInstance().setPropertyImpl(key, obj, false);
760 * Sets a property value, and optionally also saves the current properties to
768 private Object setPropertyImpl(String key, String obj, boolean andSave)
770 Object oldValue = null;
773 oldValue = applicationProperties.setProperty(key, obj);
774 if (andSave && !propsAreReadOnly && propertiesFile != null)
776 FileOutputStream out = new FileOutputStream(propertiesFile);
777 applicationProperties.store(out, "---JalviewX Properties File---");
780 } catch (Exception ex)
783 "Error setting property: " + key + " " + obj + "\n" + ex);
789 * Removes the specified property from the jalview properties file
793 public static void removeProperty(String key)
795 getInstance().removePropertyImpl(key, true);
799 * Removes the named property for the running application, without saving the
802 * Called by Preferences.ok_actionPerformed specifically for SEQUENCE_LINKS and STORED_LINKS.
807 public static void removePropertyNoSave(String key)
809 getInstance().removePropertyImpl(key, false);
813 * Removes the named property, and optionally saves the current properties to
819 private void removePropertyImpl(String key, boolean andSave)
821 applicationProperties.remove(key);
824 savePropertiesImpl();
829 * Saves the current properties to file
831 public static void saveProperties()
833 getInstance().savePropertiesImpl();
837 * save the properties to the jalview properties path
839 private void savePropertiesImpl()
841 if (!propsAreReadOnly)
845 FileOutputStream out = new FileOutputStream(propertiesFile);
846 applicationProperties.store(out, "---JalviewX Properties File---");
848 } catch (Exception ex)
850 System.out.println("Error saving properties: " + ex);
855 private final static int UNTESTED = -1;
857 private final static int TRUE = 1;
859 private final static int FALSE = 0;
862 * internal vamsas class discovery state
864 private static int vamsasJarsArePresent = (Platform.isJS() ? FALSE
868 * Searches for vamsas client classes on class path.
870 * @return true if vamsas client is present on classpath
872 public static boolean vamsasJarsPresent()
874 if (vamsasJarsArePresent == UNTESTED)
878 if (jalview.jbgui.GDesktop.class.getClassLoader()
879 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
881 jalview.bin.Cache.log.debug(
882 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
883 vamsasJarsArePresent = TRUE;
884 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
885 lvclient.setLevel(Level.toLevel(Cache
886 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
888 lvclient.addAppender(log.getAppender("JalviewLogger"));
889 // Tell the user that debug is enabled
890 lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
892 } catch (Exception e)
894 vamsasJarsArePresent = FALSE;
895 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
898 return (vamsasJarsArePresent == TRUE);
902 * internal vamsas class discovery state
904 private static int groovyJarsArePresent = (Platform.isJS() ? FALSE
908 * Searches for vamsas client classes on class path.
910 * @return true if vamsas client is present on classpath
912 public static boolean groovyJarsPresent()
914 if (groovyJarsArePresent == UNTESTED)
918 if (Cache.class.getClassLoader()
919 .loadClass("groovy.lang.GroovyObject") != null)
921 jalview.bin.Cache.log.debug(
922 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
923 groovyJarsArePresent = TRUE;
924 Logger lgclient = Logger.getLogger("groovy");
925 lgclient.setLevel(Level.toLevel(Cache
926 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
928 lgclient.addAppender(log.getAppender("JalviewLogger"));
929 // Tell the user that debug is enabled
930 lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
934 groovyJarsArePresent = FALSE;
935 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
936 } catch (Exception e)
938 groovyJarsArePresent = FALSE;
939 jalview.bin.Cache.log.debug("Groovy Classes are not present");
942 return (groovyJarsArePresent == TRUE);
946 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
949 protected static Object tracker = null;
951 protected static Class<?> trackerfocus = null;
953 protected static Class<?> jgoogleanalyticstracker = null;
956 * Initialise the google tracker if it is not done already.
958 public static void initGoogleTracker()
961 // TODO: SwingJS JavaScript tracker?
965 if (jgoogleanalyticstracker == null)
967 // try to get the tracker class
970 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
971 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
972 trackerfocus = Cache.class.getClassLoader()
973 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
974 } catch (Exception e)
977 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
979 jgoogleanalyticstracker = null;
984 // now initialise tracker
985 Exception re = null, ex = null;
987 String vrs = "No Version Accessible";
990 // Google analytics tracking code for Library Finder
991 tracker = jgoogleanalyticstracker
992 .getConstructor(new Class[]
993 { String.class, String.class, String.class })
994 .newInstance(new Object[]
996 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
997 + jalview.bin.Cache.getDefault("BUILD_DATE",
1000 jgoogleanalyticstracker
1001 .getMethod("trackAsynchronously", new Class[]
1003 .invoke(tracker, new Object[]
1004 { trackerfocus.getConstructor(new Class[] { String.class })
1005 .newInstance(new Object[]
1006 { "Application Started." }) });
1007 } catch (RuntimeException e)
1010 } catch (Exception e)
1017 if (re != null || ex != null || err != null)
1023 log.debug("Caught runtime exception in googletracker init:",
1029 "Failed to initialise GoogleTracker for Jalview Desktop with version "
1036 "Whilst initing GoogleTracker for Jalview Desktop version "
1046 "Debug: Caught runtime exception in googletracker init:"
1048 re.printStackTrace();
1053 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
1055 ex.printStackTrace();
1061 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1063 err.printStackTrace();
1069 log.debug("Successfully initialised tracker.");
1075 * Returns the Color value of the given property's value, or the supplied
1076 * default colour if no property is found, or it cannot be parsed to a colour.
1077 * Colours are normally saved as hex rgb values, though other formats may be
1084 public static Color getDefaultColour(String property, Color defcolour)
1086 String colprop = getProperty(property);
1087 if (colprop == null)
1091 Color col = ColorUtils.parseColourString(colprop);
1094 log.warn("Couldn't parse '" + colprop + "' as a colour for "
1097 return (col == null) ? defcolour : col;
1101 * Stores a colour as a Jalview property, converted to hex values for rgb.
1102 * Properties are not saved to file.
1106 * Used extensively in Preferences.ok_actionPerformed
1111 public static void setColourPropertyNoSave(String property, Color colour)
1113 setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
1117 * store a colour as a Jalview user default property
1122 public static void setColourProperty(String property, Color colour)
1124 setProperty(property, jalview.util.Format.getHexString(colour));
1128 * Stores a formatted date in a jalview property, using a fixed locale.
1129 * Updated properties are written out to the properties file.
1131 * @param propertyName
1133 * @return the formatted date string
1135 public static String setDateProperty(String propertyName, Date date)
1137 String formatted = date_format.format(date);
1138 setProperty(propertyName, formatted);
1143 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1144 * format) and returns as a Date, or null if parsing fails
1146 * @param propertyName
1150 public static Date getDateProperty(String propertyName)
1152 String val = getProperty(propertyName);
1157 return date_format.parse(val);
1158 } catch (Exception ex)
1160 System.err.println("Invalid or corrupt date in property '"
1161 + propertyName + "' : value was '" + val + "'");
1168 * get and parse a property as an integer. send any parsing problems to
1172 * @return null or Integer
1174 public static Integer getIntegerProperty(String property)
1176 String val = getProperty(property);
1177 if (val != null && (val = val.trim()).length() > 0)
1181 return Integer.valueOf(val);
1182 } catch (NumberFormatException x)
1184 System.err.println("Invalid integer in property '" + property
1185 + "' (value was '" + val + "')");
1192 * Set the specified value, or remove it if null or empty. Does not save the
1198 public static void setOrRemove(String propName, String value)
1200 if (propName == null)
1204 if (value == null || value.trim().length() < 1)
1206 getInstance().applicationProperties.remove(propName);
1210 getInstance().applicationProperties.setProperty(propName, value);
1215 * Loads in user colour schemes from files.
1218 * a '|'-delimited list of file paths
1220 public static void initUserColourSchemes(String files)
1222 if (files == null || files.length() == 0)
1227 // In case colours can't be loaded, we'll remove them
1228 // from the default list here.
1229 StringBuffer coloursFound = new StringBuffer();
1230 StringTokenizer st = new StringTokenizer(files, "|");
1231 while (st.hasMoreElements())
1233 String file = st.nextToken();
1236 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1239 if (coloursFound.length() > 0)
1241 coloursFound.append("|");
1243 coloursFound.append(file);
1244 ColourSchemes.getInstance().registerColourScheme(ucs);
1246 } catch (Exception ex)
1248 System.out.println("Error loading User ColourFile\n" + ex);
1251 if (!files.equals(coloursFound.toString()))
1253 if (coloursFound.toString().length() > 1)
1255 // BH moved to Preferences for consistency
1256 setProperty(Preferences.USER_DEFINED_COLOURS,
1257 coloursFound.toString());
1261 // BH moved to Preferences for consistency
1262 getInstance().applicationProperties
1263 .remove(Preferences.USER_DEFINED_COLOURS);
1269 * Initial logging information helper for various versions output
1273 * @param defaultValue
1275 private static void appendIfNotNull(StringBuilder sb, String prefix,
1276 String value, String suffix, String defaultValue)
1278 if (value == null && defaultValue == null)
1282 String line = prefix + (value != null ? value : defaultValue) + suffix;
1288 * @return Jalview version, build details and JVM platform version for console
1290 public static String getVersionDetailsForConsole()
1292 StringBuilder sb = new StringBuilder();
1293 sb.append("Jalview Version: " + jalview.bin.Cache.getDefault("VERSION", "TEST"));
1295 sb.append("Jalview Installation: "
1296 + jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1298 sb.append("Build Date: " + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1300 sb.append("Java version: " + System.getProperty("java.version"));
1302 sb.append(System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
1304 appendIfNotNull(sb, "Install4j version: ",
1305 System.getProperty("sys.install4jVersion"), "\n", null);
1306 appendIfNotNull(sb, "Install4j template version: ",
1307 System.getProperty("installer_template_version"), "\n", null);
1308 appendIfNotNull(sb, "Launcher version: ",
1309 System.getProperty("launcher_version"), "\n", null);
1310 if (jalview.bin.Cache.getDefault("VERSION", "TEST").equals("DEVELOPMENT")) {
1311 appendIfNotNull(sb, "Getdown appdir: ",
1312 System.getProperty("getdownappdir"), "\n", null);
1313 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1316 return sb.toString();
1321 * @return build details as reported in splashscreen
1323 public static String getBuildDetailsForSplash()
1325 // consider returning more human friendly info
1326 // eg 'built from Source' or update channel
1327 return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1331 * retrieve a dimension, such as for Jmol
1337 public static Dimension getDefaultDim(String property, Dimension def)
1339 String s = getProperty(property);
1342 if (s.indexOf(',') < 0)
1344 s = s.trim().replace(' ', ',');
1345 if (s.indexOf(',') < 0)
1352 int pt = s.indexOf(",");
1353 return new Dimension(Integer.parseInt(s.substring(0, pt)),
1354 Integer.parseInt(s.substring(pt + 1)));
1355 } catch (NumberFormatException e)
1357 System.out.println("Error parsing Dimension property '" + property
1358 + "' with value '" + s + "'");