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 jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
24 import jalview.datamodel.PDBEntry;
25 import jalview.gui.Preferences;
26 import jalview.schemes.ColourSchemeLoader;
27 import jalview.schemes.ColourSchemes;
28 import jalview.schemes.UserColourScheme;
29 import jalview.structure.StructureImportSettings;
30 import jalview.urls.IdOrgSettings;
31 import jalview.util.ColorUtils;
32 import jalview.util.Platform;
33 import jalview.ws.sifts.SiftsSettings;
35 import java.awt.Color;
36 import java.awt.Dimension;
37 import java.io.BufferedReader;
39 import java.io.FileInputStream;
40 import java.io.FileOutputStream;
41 import java.io.InputStream;
42 import java.io.InputStreamReader;
43 import java.text.DateFormat;
44 import java.text.SimpleDateFormat;
45 import java.util.Collections;
46 import java.util.Date;
47 import java.util.Enumeration;
48 import java.util.Locale;
49 import java.util.Properties;
50 import java.util.StringTokenizer;
51 import java.util.TreeSet;
53 import org.apache.log4j.ConsoleAppender;
54 import org.apache.log4j.Level;
55 import org.apache.log4j.Logger;
56 import org.apache.log4j.SimpleLayout;
59 * Stores and retrieves Jalview Application Properties Lists and fields within
60 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
61 * are alternative values for a tag. <br>
63 * Current properties include:
66 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
67 * logging level for axis (used for web services) <br>
69 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
70 * the logging level for castor (used for serialization) <br>
72 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
74 * <li>SCREEN_WIDTH</li>
75 * <li>SCREEN_HEIGHT</li>
76 * <li>SCREEN_Y=285</li>
77 * <li>SCREEN_X=371</li>
78 * <li>SHOW_FULLSCREEN boolean</li>
79 * <li>FONT_NAME java font name for alignment text display</li>
80 * <li>FONT_SIZE size of displayed alignment text</li>
81 * <li>FONT_STYLE style of font displayed (sequence labels are always
83 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
84 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
85 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
86 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
87 * <li>SHOW_IDENTITY show percentage identity annotation</li>
88 * <li>SHOW_QUALITY show alignment quality annotation</li>
89 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
90 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
91 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
92 * LABEL_AND_SEQUENCE</li>
93 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
94 * sequence annotations</li>
95 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
97 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
98 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
99 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
100 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
101 * <li>VERSION the version of the jalview build</li>
102 * <li>BUILD_DATE date of this build</li>
103 * <li>LATEST_VERSION the latest jalview version advertised on the
104 * www.jalview.org</li>
105 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
107 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
108 * suffix to file</li>
109 * <li>RECENT_URL list of recently retrieved URLs</li>
110 * <li>RECENT_FILE list of recently opened files</li>
111 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
112 * <li>PROXY_SERVER the proxy</li>
113 * <li>PROXY_PORT</li>
114 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
116 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
118 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
119 * collecting usage statistics</li>
120 * <li>SHOW_OVERVIEW boolean for overview window display</li>
121 * <li>ANTI_ALIAS boolean for smooth fonts</li>
122 * <li>RIGHT_ALIGN_IDS boolean</li>
123 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
124 * <li>PAD_GAPS boolean</li>
125 * <li>ID_ITALICS boolean</li>
126 * <li>SHOW_JV_SUFFIX</li>
127 * <li>WRAP_ALIGNMENT</li>
128 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
130 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
131 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
133 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
135 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
136 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
137 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
138 * jalview.utils.GroupURLLink for more info</li>
139 * <li>DEFAULT_BROWSER for unix</li>
140 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
142 * <li>VERSION_CHECK (true) check for the latest release version from
143 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
144 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
146 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
148 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
149 * displayed as '.'</li>
150 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
151 * order of a newly displayed tree</li>
152 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
153 * sequence ID strings before attempting retrieval from any datasource</li>
154 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
156 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
157 * in the alignment.</li>
158 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
160 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
162 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
163 * logo normalised to row height rather than histogram height.</li>
164 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
165 * respond to selections made in other alignments containing the same sequences.
167 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
168 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
169 * warning dialog box is displayed.</li>
170 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
171 * when shading by annotation</li>
172 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
173 * when shading by annotation</li>
174 * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
175 * requests to be redirected to a mirror of http://www.jalview.org</li>
176 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
177 * alignment figure to accommodate even the longest sequence ID or annotation
179 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
180 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
181 * will override this).</li>
182 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
184 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
185 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
187 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
189 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
191 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
192 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
196 * Deprecated settings:
199 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
200 * startup (JWS1 services only)</li>
201 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
202 * (JWS1 services only)</li>
203 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
204 * services in the desktop GUI</li>
205 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
206 * panel in web service preferences</li>
210 * @version $Revision$
212 public class Cache implements ApplicationSingletonI
221 * In Java, this will be a static field instance, which will be
222 * application-specific; in JavaScript it will be an applet-specific instance
223 * tied to the applet's ThreadGroup.
227 private static Cache getInstance()
229 return (Cache) ApplicationSingletonProvider.getInstance(Cache.class);
233 * property giving log4j level for CASTOR loggers
235 public static final String CASTORLOGLEVEL = "logs.Castor.level";
238 * property giving log4j level for AXIS loggers
240 public static final String AXISLOGLEVEL = "logs.Axis.level";
243 * property giving log4j level for Jalview Log
245 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
250 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
251 .getProperty("user.home") + File.separatorChar
252 + ".sifts_downloads" + File.separatorChar;
254 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
256 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
259 * Identifiers.org download settings
261 private static final String ID_ORG_FILE = System.getProperty("user.home")
262 + File.separatorChar + ".identifiers.org.ids.json";
265 * Allowed values are PDB or mmCIF
267 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
270 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
274 * a date formatter using a fixed (rather than the user's) locale;
275 * this ensures that date properties can be written and re-read successfully
276 * even if the user changes their locale setting
278 private static final DateFormat date_format = SimpleDateFormat
279 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
280 SimpleDateFormat.MEDIUM, Locale.UK);
283 * Initialises the Jalview Application Log
285 public static Logger log;
287 /** Jalview Properties */
288 // BH 2019.05.08 was static
289 @SuppressWarnings("serial")
290 private Properties applicationProperties = new Properties()
292 // override results in properties output in alphabetical order
294 public synchronized Enumeration<Object> keys()
296 return Collections.enumeration(new TreeSet<>(super.keySet()));
300 /** Default file is ~/.jalview_properties */
301 private String propertiesFile;
304 * flag to possibly allow properties to be written to a property file
306 private boolean propsAreReadOnly = Platform.isJS();
308 private final static String JS_PROPERTY_PREFIX = "jalview_";
310 public static void initLogger()
318 // TODO: redirect stdout and stderr here in order to grab the output of
321 ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
323 ap.setName("JalviewLogger");
324 org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
326 Logger laxis = Logger.getLogger("org.apache.axis");
327 Logger lcastor = Logger.getLogger("org.exolab.castor");
328 jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
330 laxis.setLevel(Level.toLevel(
331 getDefault("logs.Axis.Level", Level.INFO.toString())));
332 lcastor.setLevel(Level.toLevel(
333 getDefault("logs.Castor.Level", Level.INFO.toString())));
334 lcastor = Logger.getLogger("org.exolab.castor.xml");
335 lcastor.setLevel(Level.toLevel(
336 getDefault("logs.Castor.Level", Level.INFO.toString())));
337 // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
338 // lcastor.setLevel(Level.toLevel(getDefault("logs.Castor.Level",
339 // Level.INFO.toString())));
340 jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
341 .getDefault("logs.Jalview.level", Level.INFO.toString())));
342 // laxis.addAppender(ap);
343 // lcastor.addAppender(ap);
344 // jalview.bin.Cache.log.addAppender(ap);
345 // Tell the user that debug is enabled
346 jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
347 } catch (Exception ex)
349 System.err.println("Problems initializing the log4j system\n");
350 ex.printStackTrace(System.err);
355 * Loads properties from the given properties file. Any existing properties
358 public static void loadProperties(String propsFile)
360 getInstance().loadPropertiesImpl(propsFile);
363 private void loadPropertiesImpl(String propsFile)
365 propertiesFile = propsFile;
366 if (!propsAreReadOnly)
369 if (propsFile == null)
371 propertiesFile = System.getProperty("user.home")
372 + File.separatorChar + ".jalview_properties";
376 // don't corrupt the file we've been given.
377 propsAreReadOnly = true;
381 if (propertiesFile == null)
382 { // BH 2019 read properties from the Info object associated with this
384 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
385 applicationProperties);
394 fis = new java.net.URL(propertiesFile).openStream();
396 "Loading jalview properties from : " + propertiesFile);
398 "Disabling Jalview writing to user's local properties file.");
399 propsAreReadOnly = true;
401 } catch (Exception ex)
407 fis = new FileInputStream(propertiesFile);
409 applicationProperties.clear();
410 applicationProperties.load(fis);
412 // remove any old build properties
414 deleteBuildProperties();
416 } catch (Exception ex)
418 System.out.println("Error reading properties file: " + ex);
421 if (getDefault("USE_PROXY", false))
423 String proxyServer = getDefault("PROXY_SERVER", ""),
424 proxyPort = getDefault("PROXY_PORT", "8080");
426 System.out.println("Using proxyServer: " + proxyServer
427 + " proxyPort: " + proxyPort);
429 System.setProperty("http.proxyHost", proxyServer);
430 System.setProperty("http.proxyPort", proxyPort);
433 // LOAD THE AUTHORS FROM THE authors.props file
434 String authorDetails = (Platform.isJS() ? null
435 : "jar:".concat(Cache.class.getProtectionDomain()
436 .getCodeSource().getLocation().toString()
437 .concat("!/authors.props")));
441 if (authorDetails != null)
443 java.net.URL localJarFileURL = new java.net.URL(authorDetails);
444 InputStream in = localJarFileURL.openStream();
445 applicationProperties.load(in);
448 } catch (Exception ex)
450 System.out.println("Error reading author details: " + ex);
451 authorDetails = null;
453 if (authorDetails == null)
455 applicationProperties.remove("AUTHORS");
456 applicationProperties.remove("AUTHORFNAMES");
457 applicationProperties.remove("YEAR");
460 // FIND THE VERSION NUMBER AND BUILD DATE FROM jalview.jar
461 // MUST FOLLOW READING OF LOCAL PROPERTIES FILE AS THE
462 // VERSION MAY HAVE CHANGED SINCE LAST USING JALVIEW
463 String buildDetails = (Platform.isJS() ? null
464 : "jar:".concat(Cache.class.getProtectionDomain()
465 .getCodeSource().getLocation().toString()
466 .concat("!/.build_properties")));
467 if (buildDetails != null)
471 java.net.URL localJarFileURL = new java.net.URL(buildDetails);
472 InputStream in = localJarFileURL.openStream();
473 applicationProperties.load(in);
475 } catch (Exception ex)
477 System.out.println("Error reading build details: " + ex);
481 if (buildDetails == null)
483 applicationProperties.remove("VERSION");
485 String jnlpVersion = System.getProperty("jalview.version");
486 String codeVersion = getProperty("VERSION");
487 String codeInstallation = getProperty("INSTALLATION");
488 if (codeVersion == null)
490 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
491 codeVersion = "Test";
492 jnlpVersion = "Test";
493 codeInstallation = "";
497 codeInstallation = " (" + codeInstallation + ")";
499 new BuildDetails(codeVersion, null, codeInstallation);
501 SiftsSettings.setMapWithSifts(getDefault("MAP_WITH_SIFTS", false));
503 SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
504 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
506 SiftsSettings.setFailSafePIDThreshold(
507 getDefault("sifts_fail_safe_pid_threshold",
508 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
510 SiftsSettings.setCacheThresholdInDays(
511 getDefault("sifts_cache_threshold_in_days",
512 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
514 IdOrgSettings.setUrl(getDefault(Preferences.ID_ORG_HOSTURL,
515 "http://www.jalview.org/services/identifiers"));
516 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
519 .println("Jalview Version: " + codeVersion + codeInstallation);
521 StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
522 .getDefault(Preferences.PDB_DOWNLOAD_FORMAT, PDB_DOWNLOAD_FORMAT));
523 StructureImportSettings
524 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
525 // StructureImportSettings
526 // .setDefaultPDBFileParser(jalview.bin.getDefault(
527 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
528 // jnlpVersion will be null if we're using InstallAnywhere
529 // Dont do this check if running in headless mode
530 if (jnlpVersion == null && !Jalview.isHeadlessMode()
531 && getDefault("VERSION_CHECK", true))
534 class VersionChecker extends Thread
539 String orgtimeout = System
540 .getProperty("sun.net.client.defaultConnectTimeout");
541 if (orgtimeout == null)
544 System.out.println("# INFO: Setting default net timeout to "
545 + orgtimeout + " seconds.");
547 String remoteVersion = null;
550 System.setProperty("sun.net.client.defaultConnectTimeout",
552 java.net.URL url = new java.net.URL(Cache
553 .getDefault("www.jalview.org", "http://www.jalview.org")
554 + "/webstart/jalview.jnlp");
555 BufferedReader in = new BufferedReader(
556 new InputStreamReader(url.openStream()));
558 while ((line = in.readLine()) != null)
560 if (line.indexOf("jalview.version") == -1)
565 line = line.substring(line.indexOf("value=") + 7);
566 line = line.substring(0, line.lastIndexOf("\""));
567 remoteVersion = line;
570 } catch (Exception ex)
573 "Non-fatal exception when checking version at www.jalview.org :");
574 System.out.println(ex);
575 remoteVersion = getProperty("VERSION");
577 System.setProperty("sun.net.client.defaultConnectTimeout",
580 setProperty("LATEST_VERSION", remoteVersion);
584 VersionChecker vc = new VersionChecker();
589 if (jnlpVersion != null)
591 setProperty("LATEST_VERSION", jnlpVersion);
595 applicationProperties.remove("LATEST_VERSION");
599 setProperty("VERSION", codeVersion);
601 // LOAD USERDEFINED COLOURS
602 initUserColourSchemes(getProperty(Preferences.USER_DEFINED_COLOURS));
605 private void deleteBuildProperties()
607 applicationProperties.remove("LATEST_VERSION");
608 applicationProperties.remove("VERSION");
609 applicationProperties.remove("AUTHORS");
610 applicationProperties.remove("AUTHORFNAMES");
611 applicationProperties.remove("YEAR");
612 applicationProperties.remove("BUILD_DATE");
613 applicationProperties.remove("INSTALLATION");
617 * Gets Jalview application property of given key. Returns null if key not
623 * @return Property value
625 public static String getProperty(String key)
627 return getInstance().applicationProperties.getProperty(key);
631 * These methods are used when checking if the saved preference is different
632 * to the default setting
635 public static boolean getDefault(String property, boolean def)
637 String string = getProperty(property);
640 def = Boolean.valueOf(string).booleanValue();
646 public static int getDefault(String property, int def)
648 String string = getProperty(property);
653 def = Integer.parseInt(string);
654 } catch (NumberFormatException e)
656 System.out.println("Error parsing int property '" + property
657 + "' with value '" + string + "'");
665 * retrieve a dimension, such as for Jmol
671 public static Dimension getDefaultDim(String property, Dimension def)
673 String s = getProperty(property);
676 if (s.indexOf(',') < 0)
678 s = s.trim().replace(' ', ',');
679 if (s.indexOf(',') < 0)
686 int pt = s.indexOf(",");
687 return new Dimension(Integer.parseInt(s.substring(0, pt)),
688 Integer.parseInt(s.substring(pt + 1)));
689 } catch (NumberFormatException e)
691 System.out.println("Error parsing Dimension property '" + property
692 + "' with value '" + s + "'");
699 * Answers the value of the given property, or the supplied default value if
700 * the property is not set
702 public static String getDefault(String property, String def)
704 String value = getProperty(property);
705 return value == null ? def : value;
709 * Stores property in the file "HOME_DIR/.jalview_properties"
714 * String value of property
716 * @return previous value of property (or null)
718 public static Object setProperty(String key, String obj)
720 return getInstance().setPropertyImpl(key, obj, true);
723 public static void setPropertyNoSave(String key, String obj)
725 getInstance().setPropertyImpl(key, obj, false);
728 private Object setPropertyImpl(String key, String obj, boolean andSave)
730 Object oldValue = null;
733 oldValue = applicationProperties.setProperty(key, obj);
734 if (andSave && !propsAreReadOnly && propertiesFile != null)
736 FileOutputStream out = new FileOutputStream(propertiesFile);
737 applicationProperties.store(out, "---JalviewX Properties File---");
740 } catch (Exception ex)
743 "Error setting property: " + key + " " + obj + "\n" + ex);
749 * remove the specified property from the jalview properties file
753 public static void removeProperty(String key)
755 getInstance().removePropertyImpl(key, true);
758 public static void removePropertyNoSave(String key)
760 getInstance().removePropertyImpl(key, false);
763 private void removePropertyImpl(String key, boolean andSave)
765 applicationProperties.remove(key);
768 savePropertiesImpl();
772 public static void saveProperties()
774 getInstance().savePropertiesImpl();
778 * save the properties to the jalview properties path
780 private void savePropertiesImpl()
782 if (!propsAreReadOnly)
786 FileOutputStream out = new FileOutputStream(propertiesFile);
787 applicationProperties.store(out, "---JalviewX Properties File---");
789 } catch (Exception ex)
791 System.out.println("Error saving properties: " + ex);
796 private final static int UNTESTED = -1;
798 private final static int TRUE = 1;
800 private final static int FALSE = 0;
803 * internal vamsas class discovery state
805 private static int vamsasJarsArePresent = (Platform.isJS() ? FALSE
809 * Searches for vamsas client classes on class path.
811 * @return true if vamsas client is present on classpath
813 public static boolean vamsasJarsPresent()
815 if (vamsasJarsArePresent == UNTESTED)
819 if (jalview.jbgui.GDesktop.class.getClassLoader()
820 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
822 jalview.bin.Cache.log.debug(
823 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
824 vamsasJarsArePresent = TRUE;
825 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
826 lvclient.setLevel(Level.toLevel(Cache
827 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
829 lvclient.addAppender(log.getAppender("JalviewLogger"));
830 // Tell the user that debug is enabled
831 lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
833 } catch (Exception e)
835 vamsasJarsArePresent = FALSE;
836 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
839 return (vamsasJarsArePresent == TRUE);
843 * internal vamsas class discovery state
845 private static int groovyJarsArePresent = (Platform.isJS() ? FALSE
849 * Searches for vamsas client classes on class path.
851 * @return true if vamsas client is present on classpath
853 public static boolean groovyJarsPresent()
855 if (groovyJarsArePresent == UNTESTED)
859 if (Cache.class.getClassLoader()
860 .loadClass("groovy.lang.GroovyObject") != null)
862 jalview.bin.Cache.log.debug(
863 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
864 groovyJarsArePresent = TRUE;
865 Logger lgclient = Logger.getLogger("groovy");
866 lgclient.setLevel(Level.toLevel(Cache
867 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
869 lgclient.addAppender(log.getAppender("JalviewLogger"));
870 // Tell the user that debug is enabled
871 lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
875 groovyJarsArePresent = FALSE;
876 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
877 } catch (Exception e)
879 groovyJarsArePresent = FALSE;
880 jalview.bin.Cache.log.debug("Groovy Classes are not present");
883 return (groovyJarsArePresent == TRUE);
887 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
890 protected static Object tracker = null;
892 protected static Class<?> trackerfocus = null;
894 protected static Class<?> jgoogleanalyticstracker = null;
897 * Initialise the google tracker if it is not done already.
899 public static void initGoogleTracker()
902 // TODO: SwingJS JavaScript tracker?
906 if (jgoogleanalyticstracker == null)
908 // try to get the tracker class
911 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
912 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
913 trackerfocus = Cache.class.getClassLoader()
914 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
915 } catch (Exception e)
918 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
920 jgoogleanalyticstracker = null;
925 // now initialise tracker
926 Exception re = null, ex = null;
928 String vrs = "No Version Accessible";
931 // Google analytics tracking code for Library Finder
932 tracker = jgoogleanalyticstracker
933 .getConstructor(new Class[]
934 { String.class, String.class, String.class })
935 .newInstance(new Object[]
937 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
938 + getDefault("BUILD_DATE", "unknown")),
940 jgoogleanalyticstracker
941 .getMethod("trackAsynchronously", new Class[]
943 .invoke(tracker, new Object[]
944 { trackerfocus.getConstructor(new Class[] { String.class })
945 .newInstance(new Object[]
946 { "Application Started." }) });
947 } catch (RuntimeException e)
950 } catch (Exception e)
957 if (re != null || ex != null || err != null)
963 log.debug("Caught runtime exception in googletracker init:",
969 "Failed to initialise GoogleTracker for Jalview Desktop with version "
976 "Whilst initing GoogleTracker for Jalview Desktop version "
986 "Debug: Caught runtime exception in googletracker init:"
988 re.printStackTrace();
993 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
995 ex.printStackTrace();
1001 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1003 err.printStackTrace();
1009 log.debug("Successfully initialised tracker.");
1015 * get the user's default colour if available
1021 public static Color getDefaultColour(String property, Color defcolour)
1023 String colprop = getProperty(property);
1024 if (colprop == null)
1028 Color col = ColorUtils.parseColourString(colprop);
1031 log.warn("Couldn't parse '" + colprop + "' as a colour for "
1034 return (col == null) ? defcolour : col;
1038 * store a colour as a Jalview user default property
1043 public static void setColourProperty(String property, Color colour)
1045 setProperty(property, jalview.util.Format.getHexString(colour));
1049 * Stores a formatted date in a jalview property, using a fixed locale.
1051 * @param propertyName
1053 * @return the formatted date string
1055 public static String setDateProperty(String propertyName, Date date)
1057 String formatted = date_format.format(date);
1058 setProperty(propertyName, formatted);
1063 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1064 * format) and returns as a Date, or null if parsing fails
1066 * @param propertyName
1070 public static Date getDateProperty(String propertyName)
1072 String val = getProperty(propertyName);
1077 return date_format.parse(val);
1078 } catch (Exception ex)
1080 System.err.println("Invalid or corrupt date in property '"
1081 + propertyName + "' : value was '" + val + "'");
1088 * get and parse a property as an integer. send any parsing problems to
1092 * @return null or Integer
1094 public static Integer getIntegerProperty(String property)
1096 String val = getProperty(property);
1097 if (val != null && (val = val.trim()).length() > 0)
1101 return Integer.valueOf(val);
1102 } catch (NumberFormatException x)
1104 System.err.println("Invalid integer in property '" + property
1105 + "' (value was '" + val + "')");
1112 * Set the specified value, or remove it if null or empty. Does not save the
1118 public static void setOrRemove(String propName, String value)
1120 if (propName == null)
1124 if (value == null || value.trim().length() < 1)
1126 getInstance().applicationProperties.remove(propName);
1130 getInstance().applicationProperties.setProperty(propName, value);
1135 * Loads in user colour schemes from files.
1138 * a '|'-delimited list of file paths
1140 public static void initUserColourSchemes(String files)
1142 if (files == null || files.length() == 0)
1147 // In case colours can't be loaded, we'll remove them
1148 // from the default list here.
1149 StringBuffer coloursFound = new StringBuffer();
1150 StringTokenizer st = new StringTokenizer(files, "|");
1151 while (st.hasMoreElements())
1153 String file = st.nextToken();
1156 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1159 if (coloursFound.length() > 0)
1161 coloursFound.append("|");
1163 coloursFound.append(file);
1164 ColourSchemes.getInstance().registerColourScheme(ucs);
1166 } catch (Exception ex)
1168 System.out.println("Error loading User ColourFile\n" + ex);
1171 if (!files.equals(coloursFound.toString()))
1173 if (coloursFound.toString().length() > 1)
1175 setProperty(Preferences.USER_DEFINED_COLOURS,
1176 coloursFound.toString());
1180 getInstance().applicationProperties
1181 .remove(Preferences.USER_DEFINED_COLOURS);