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);
745 * Sets a property value for the running application, without saving it to the
748 * Replaces direct call to Cache.applicationProperties.setProperty
750 * Used extensively in AppletParams and Preferences.ok_actionPerformed
756 public static void setPropertyNoSave(String key, String obj)
758 getInstance().setPropertyImpl(key, obj, false);
763 * Sets a property value, and optionally also saves the current properties to
771 private Object setPropertyImpl(String key, String obj, boolean andSave)
773 Object oldValue = null;
776 oldValue = applicationProperties.setProperty(key, obj);
777 if (andSave && !propsAreReadOnly && propertiesFile != null)
779 FileOutputStream out = new FileOutputStream(propertiesFile);
780 applicationProperties.store(out, "---JalviewX Properties File---");
783 } catch (Exception ex)
786 "Error setting property: " + key + " " + obj + "\n" + ex);
792 * Removes the specified property from the jalview properties file
796 public static void removeProperty(String key)
798 getInstance().removePropertyImpl(key, true);
802 * Removes the named property for the running application, without saving the
805 * Called by Preferences.ok_actionPerformed specifically for SEQUENCE_LINKS and STORED_LINKS.
810 public static void removePropertyNoSave(String key)
812 getInstance().removePropertyImpl(key, false);
816 * Removes the named property, and optionally saves the current properties to
822 private void removePropertyImpl(String key, boolean andSave)
824 applicationProperties.remove(key);
827 savePropertiesImpl();
832 * Saves the current properties to file
834 public static void saveProperties()
836 getInstance().savePropertiesImpl();
840 * save the properties to the jalview properties path
842 private void savePropertiesImpl()
844 if (!propsAreReadOnly)
848 FileOutputStream out = new FileOutputStream(propertiesFile);
849 applicationProperties.store(out, "---JalviewX Properties File---");
851 } catch (Exception ex)
853 System.out.println("Error saving properties: " + ex);
858 private final static int UNTESTED = -1;
860 private final static int TRUE = 1;
862 private final static int FALSE = 0;
865 * internal vamsas class discovery state
867 private static int vamsasJarsArePresent = (Platform.isJS() ? FALSE
871 * Searches for vamsas client classes on class path.
873 * @return true if vamsas client is present on classpath
875 public static boolean vamsasJarsPresent()
877 if (vamsasJarsArePresent == UNTESTED)
881 if (jalview.jbgui.GDesktop.class.getClassLoader()
882 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
884 jalview.bin.Cache.log.debug(
885 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
886 vamsasJarsArePresent = TRUE;
887 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
888 lvclient.setLevel(Level.toLevel(Cache
889 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
891 lvclient.addAppender(log.getAppender("JalviewLogger"));
892 // Tell the user that debug is enabled
893 lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
895 } catch (Exception e)
897 vamsasJarsArePresent = FALSE;
898 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
901 return (vamsasJarsArePresent == TRUE);
905 * internal vamsas class discovery state
907 private static int groovyJarsArePresent = (Platform.isJS() ? FALSE
911 * Searches for vamsas client classes on class path.
913 * @return true if vamsas client is present on classpath
915 public static boolean groovyJarsPresent()
917 if (groovyJarsArePresent == UNTESTED)
921 if (Cache.class.getClassLoader()
922 .loadClass("groovy.lang.GroovyObject") != null)
924 jalview.bin.Cache.log.debug(
925 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
926 groovyJarsArePresent = TRUE;
927 Logger lgclient = Logger.getLogger("groovy");
928 lgclient.setLevel(Level.toLevel(Cache
929 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
931 lgclient.addAppender(log.getAppender("JalviewLogger"));
932 // Tell the user that debug is enabled
933 lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
937 groovyJarsArePresent = FALSE;
938 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
939 } catch (Exception e)
941 groovyJarsArePresent = FALSE;
942 jalview.bin.Cache.log.debug("Groovy Classes are not present");
945 return (groovyJarsArePresent == TRUE);
949 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
952 protected static Object tracker = null;
954 protected static Class<?> trackerfocus = null;
956 protected static Class<?> jgoogleanalyticstracker = null;
959 * Initialise the google tracker if it is not done already.
961 public static void initGoogleTracker()
964 // TODO: SwingJS JavaScript tracker?
968 if (jgoogleanalyticstracker == null)
970 // try to get the tracker class
973 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
974 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
975 trackerfocus = Cache.class.getClassLoader()
976 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
977 } catch (Exception e)
980 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
982 jgoogleanalyticstracker = null;
987 // now initialise tracker
988 Exception re = null, ex = null;
990 String vrs = "No Version Accessible";
993 // Google analytics tracking code for Library Finder
994 tracker = jgoogleanalyticstracker
995 .getConstructor(new Class[]
996 { String.class, String.class, String.class })
997 .newInstance(new Object[]
999 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
1000 + jalview.bin.Cache.getDefault("BUILD_DATE",
1003 jgoogleanalyticstracker
1004 .getMethod("trackAsynchronously", new Class[]
1006 .invoke(tracker, new Object[]
1007 { trackerfocus.getConstructor(new Class[] { String.class })
1008 .newInstance(new Object[]
1009 { "Application Started." }) });
1010 } catch (RuntimeException e)
1013 } catch (Exception e)
1020 if (re != null || ex != null || err != null)
1026 log.debug("Caught runtime exception in googletracker init:",
1032 "Failed to initialise GoogleTracker for Jalview Desktop with version "
1039 "Whilst initing GoogleTracker for Jalview Desktop version "
1049 "Debug: Caught runtime exception in googletracker init:"
1051 re.printStackTrace();
1056 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
1058 ex.printStackTrace();
1064 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1066 err.printStackTrace();
1072 log.debug("Successfully initialised tracker.");
1078 * Returns the Color value of the given property's value, or the supplied
1079 * default colour if no property is found, or it cannot be parsed to a colour.
1080 * Colours are normally saved as hex rgb values, though other formats may be
1087 public static Color getDefaultColour(String property, Color defcolour)
1089 String colprop = getProperty(property);
1090 if (colprop == null)
1094 Color col = ColorUtils.parseColourString(colprop);
1097 log.warn("Couldn't parse '" + colprop + "' as a colour for "
1100 return (col == null) ? defcolour : col;
1104 * Stores a colour as a Jalview property, converted to hex values for rgb.
1105 * Properties are not saved to file.
1109 * Used extensively in Preferences.ok_actionPerformed
1114 public static void setColourPropertyNoSave(String property, Color colour)
1116 setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
1120 * store a colour as a Jalview user default property
1125 public static void setColourProperty(String property, Color colour)
1127 setProperty(property, jalview.util.Format.getHexString(colour));
1131 * Stores a formatted date in a jalview property, using a fixed locale.
1132 * Updated properties are written out to the properties file.
1134 * @param propertyName
1136 * @return the formatted date string
1138 public static String setDateProperty(String propertyName, Date date)
1140 String formatted = date_format.format(date);
1141 setProperty(propertyName, formatted);
1146 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1147 * format) and returns as a Date, or null if parsing fails
1149 * @param propertyName
1153 public static Date getDateProperty(String propertyName)
1155 String val = getProperty(propertyName);
1160 return date_format.parse(val);
1161 } catch (Exception ex)
1163 System.err.println("Invalid or corrupt date in property '"
1164 + propertyName + "' : value was '" + val + "'");
1171 * get and parse a property as an integer. send any parsing problems to
1175 * @return null or Integer
1177 public static Integer getIntegerProperty(String property)
1179 String val = getProperty(property);
1180 if (val != null && (val = val.trim()).length() > 0)
1184 return Integer.valueOf(val);
1185 } catch (NumberFormatException x)
1187 System.err.println("Invalid integer in property '" + property
1188 + "' (value was '" + val + "')");
1195 * Set the specified value, or remove it if null or empty. Does not save the
1201 public static void setOrRemove(String propName, String value)
1203 if (propName == null)
1207 if (value == null || value.trim().length() < 1)
1209 getInstance().applicationProperties.remove(propName);
1213 getInstance().applicationProperties.setProperty(propName, value);
1218 * Loads in user colour schemes from files.
1221 * a '|'-delimited list of file paths
1223 public static void initUserColourSchemes(String files)
1225 if (files == null || files.length() == 0)
1230 // In case colours can't be loaded, we'll remove them
1231 // from the default list here.
1232 StringBuffer coloursFound = new StringBuffer();
1233 StringTokenizer st = new StringTokenizer(files, "|");
1234 while (st.hasMoreElements())
1236 String file = st.nextToken();
1239 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1242 if (coloursFound.length() > 0)
1244 coloursFound.append("|");
1246 coloursFound.append(file);
1247 ColourSchemes.getInstance().registerColourScheme(ucs);
1249 } catch (Exception ex)
1251 System.out.println("Error loading User ColourFile\n" + ex);
1254 if (!files.equals(coloursFound.toString()))
1256 if (coloursFound.toString().length() > 1)
1258 // BH moved to Preferences for consistency
1259 setProperty(Preferences.USER_DEFINED_COLOURS,
1260 coloursFound.toString());
1264 // BH moved to Preferences for consistency
1265 getInstance().applicationProperties
1266 .remove(Preferences.USER_DEFINED_COLOURS);
1272 * Initial logging information helper for various versions output
1276 * @param defaultValue
1278 private static void appendIfNotNull(StringBuilder sb, String prefix,
1279 String value, String suffix, String defaultValue)
1281 if (value == null && defaultValue == null)
1285 String line = prefix + (value != null ? value : defaultValue) + suffix;
1291 * @return Jalview version, build details and JVM platform version for console
1293 public static String getVersionDetailsForConsole()
1295 StringBuilder sb = new StringBuilder();
1296 sb.append("Jalview Version: " + jalview.bin.Cache.getDefault("VERSION", "TEST"));
1298 sb.append("Jalview Installation: "
1299 + jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1301 sb.append("Build Date: " + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1303 sb.append("Java version: " + System.getProperty("java.version"));
1305 sb.append(System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
1307 appendIfNotNull(sb, "Install4j version: ",
1308 System.getProperty("sys.install4jVersion"), "\n", null);
1309 appendIfNotNull(sb, "Install4j template version: ",
1310 System.getProperty("installer_template_version"), "\n", null);
1311 appendIfNotNull(sb, "Launcher version: ",
1312 System.getProperty("launcher_version"), "\n", null);
1313 if (jalview.bin.Cache.getDefault("VERSION", "TEST").equals("DEVELOPMENT")) {
1314 appendIfNotNull(sb, "Getdown appdir: ",
1315 System.getProperty("getdownappdir"), "\n", null);
1316 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1319 return sb.toString();
1324 * @return build details as reported in splashscreen
1326 public static String getBuildDetailsForSplash()
1328 // consider returning more human friendly info
1329 // eg 'built from Source' or update channel
1330 return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1334 * retrieve a dimension, such as for Jmol
1340 public static Dimension getDefaultDim(String property, Dimension def)
1342 String s = getProperty(property);
1345 if (s.indexOf(',') < 0)
1347 s = s.trim().replace(' ', ',');
1348 if (s.indexOf(',') < 0)
1355 int pt = s.indexOf(",");
1356 return new Dimension(Integer.parseInt(s.substring(0, pt)),
1357 Integer.parseInt(s.substring(pt + 1)));
1358 } catch (NumberFormatException e)
1360 System.out.println("Error parsing Dimension property '" + property
1361 + "' with value '" + s + "'");