2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.Color;
24 import java.io.BufferedReader;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.PrintWriter;
31 import java.io.StringWriter;
32 import java.net.Authenticator;
33 import java.net.PasswordAuthentication;
35 import java.text.DateFormat;
36 import java.text.SimpleDateFormat;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Date;
40 import java.util.Enumeration;
41 import java.util.Locale;
42 import java.util.Properties;
43 import java.util.StringTokenizer;
44 import java.util.TreeSet;
45 import java.util.regex.Pattern;
47 import javax.swing.LookAndFeel;
48 import javax.swing.UIManager;
50 import org.apache.log4j.ConsoleAppender;
51 import org.apache.log4j.Level;
52 import org.apache.log4j.Logger;
53 import org.apache.log4j.SimpleLayout;
55 import jalview.datamodel.PDBEntry;
56 import jalview.gui.Preferences;
57 import jalview.gui.UserDefinedColours;
58 import jalview.schemes.ColourSchemeLoader;
59 import jalview.schemes.ColourSchemes;
60 import jalview.schemes.UserColourScheme;
61 import jalview.structure.StructureImportSettings;
62 import jalview.urls.IdOrgSettings;
63 import jalview.util.ChannelProperties;
64 import jalview.util.ColorUtils;
65 import jalview.util.MessageManager;
66 import jalview.util.Platform;
67 import jalview.ws.sifts.SiftsSettings;
70 * Stores and retrieves Jalview Application Properties Lists and fields within
71 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
72 * are alternative values for a tag. <br>
74 * Current properties include:
77 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
78 * logging level for axis (used for web services) <br>
80 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
81 * the logging level for castor (used for serialization) <br>
83 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
85 * <li>SCREEN_WIDTH</li>
86 * <li>SCREEN_HEIGHT</li>
87 * <li>SCREEN_Y=285</li>
88 * <li>SCREEN_X=371</li>
89 * <li>SHOW_FULLSCREEN boolean</li>
90 * <li>FONT_NAME java font name for alignment text display</li>
91 * <li>FONT_SIZE size of displayed alignment text</li>
92 * <li>FONT_STYLE style of font displayed (sequence labels are always
94 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
95 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
96 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
97 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
98 * <li>SHOW_IDENTITY show percentage identity annotation</li>
99 * <li>SHOW_QUALITY show alignment quality annotation</li>
100 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
101 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
102 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
103 * LABEL_AND_SEQUENCE</li>
104 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
105 * sequence annotations</li>
106 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
107 * annotation row</li>
108 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
109 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
110 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
111 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
112 * <li>VERSION the version of the jalview build</li>
113 * <li>BUILD_DATE date of this build</li>
114 * <li>LATEST_VERSION the latest jalview version advertised on the
115 * www.jalview.org</li>
116 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
118 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
119 * suffix to file</li>
120 * <li>RECENT_URL list of recently retrieved URLs</li>
121 * <li>RECENT_FILE list of recently opened files</li>
122 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
123 * <li>PROXY_SERVER the proxy</li>
124 * <li>PROXY_PORT</li>
125 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
127 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
129 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
130 * collecting usage statistics</li>
131 * <li>SHOW_OVERVIEW boolean for overview window display</li>
132 * <li>ANTI_ALIAS boolean for smooth fonts</li>
133 * <li>RIGHT_ALIGN_IDS boolean</li>
134 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
135 * <li>PAD_GAPS boolean</li>
136 * <li>ID_ITALICS boolean</li>
137 * <li>SHOW_JV_SUFFIX</li>
138 * <li>WRAP_ALIGNMENT</li>
139 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
141 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
142 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
144 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
146 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
147 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
148 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
149 * jalview.utils.GroupURLLink for more info</li>
150 * <li>DEFAULT_BROWSER for unix</li>
151 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
153 * <li>VERSION_CHECK (true) check for the latest release version from
154 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
155 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
157 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
159 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
160 * displayed as '.'</li>
161 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
162 * order of a newly displayed tree</li>
163 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
164 * sequence ID strings before attempting retrieval from any datasource</li>
165 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
167 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
168 * in the alignment.</li>
169 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
171 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
173 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
174 * logo normalised to row height rather than histogram height.</li>
175 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
176 * respond to selections made in other alignments containing the same sequences.
178 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
179 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
180 * warning dialog box is displayed.</li>
181 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
182 * when shading by annotation</li>
183 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
184 * when shading by annotation</li>
185 * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
186 * requests to be redirected to a mirror of http://www.jalview.org</li>
187 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
188 * alignment figure to accommodate even the longest sequence ID or annotation
190 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
191 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
192 * will override this).</li>
193 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
195 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
196 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
198 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
200 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
202 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
203 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
207 * Deprecated settings:
210 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
211 * startup (JWS1 services only)</li>
212 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
213 * (JWS1 services only)</li>
214 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
215 * services in the desktop GUI</li>
216 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
217 * panel in web service preferences</li>
221 * @version $Revision$
226 * property giving log4j level for CASTOR loggers
228 public static final String CASTORLOGLEVEL = "logs.Castor.level";
231 * property giving log4j level for AXIS loggers
233 public static final String AXISLOGLEVEL = "logs.Axis.level";
236 * property giving log4j level for Jalview Log
238 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
243 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
244 .getProperty("user.home") + File.separatorChar
245 + ".sifts_downloads" + File.separatorChar;
247 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
249 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
252 * Identifiers.org download settings
254 private static final String ID_ORG_FILE = System.getProperty("user.home")
255 + File.separatorChar + ".identifiers.org.ids.json";
258 * Allowed values are PDB or mmCIF
260 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
263 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
267 * a date formatter using a fixed (rather than the user's) locale;
268 * this ensures that date properties can be written and re-read successfully
269 * even if the user changes their locale setting
271 private static final DateFormat date_format = SimpleDateFormat
272 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
273 SimpleDateFormat.MEDIUM, Locale.UK);
276 * Initialises the Jalview Application Log
278 public static Logger log;
280 // save the proxy properties set at startup
281 public final static String[] startupProxyProperties = {
282 System.getProperty("http.proxyHost"),
283 System.getProperty("http.proxyPort"),
284 System.getProperty("https.proxyHost"),
285 System.getProperty("https.proxyPort"),
286 System.getProperty("http.proxyUser"),
287 System.getProperty("http.proxyPassword"),
288 System.getProperty("https.proxyUser"),
289 System.getProperty("https.proxyPassword"),
290 System.getProperty("http.nonProxyHosts") };
292 public final static String PROXYTYPE_NONE = "none";
294 // "false" and "true" for backward compatibility
295 public final static String PROXYTYPE_SYSTEM = "false";
297 public final static String PROXYTYPE_CUSTOM = "true";
299 // in-memory only storage of proxy password, safer to use char array
300 public static char[] proxyAuthPassword = null;
302 /** Jalview Properties */
303 public static Properties applicationProperties = new Properties()
305 // override results in properties output in alphabetical order
307 public synchronized Enumeration<Object> keys()
309 return Collections.enumeration(new TreeSet<>(super.keySet()));
313 /** Default file is ~/.jalview_properties */
314 static String propertiesFile;
316 private static boolean propsAreReadOnly = Platform.isJS();
318 private final static String JS_PROPERTY_PREFIX = "jalview_";
320 public static void initLogger()
328 // TODO: redirect stdout and stderr here in order to grab the output of
331 ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
333 ap.setName("JalviewLogger");
334 org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
336 Logger laxis = Logger.getLogger("org.apache.axis");
337 Logger lcastor = Logger.getLogger("org.exolab.castor");
338 jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
340 laxis.setLevel(Level.toLevel(
341 Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
342 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
343 Level.INFO.toString())));
344 lcastor = Logger.getLogger("org.exolab.castor.xml");
345 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
346 Level.INFO.toString())));
347 // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
348 // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
349 // Level.INFO.toString())));
350 // we shouldn't need to do this
351 org.apache.log4j.Logger.getRootLogger()
352 .setLevel(org.apache.log4j.Level.INFO);
354 jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
355 .getDefault("logs.Jalview.level", Level.INFO.toString())));
356 // laxis.addAppender(ap);
357 // lcastor.addAppender(ap);
358 // jalview.bin.Cache.log.addAppender(ap);
359 // Tell the user that debug is enabled
360 jalview.bin.Cache.log.debug(ChannelProperties.getProperty("app_name")
361 + " Debugging Output Follows.");
362 } catch (Exception ex)
364 System.err.println("Problems initializing the log4j system\n");
365 ex.printStackTrace(System.err);
370 * Loads properties from the given properties file. Any existing properties
373 public static void loadProperties(String propsFile)
375 propertiesFile = propsFile;
376 if (propsFile == null && !propsAreReadOnly)
378 propertiesFile = System.getProperty("user.home") + File.separatorChar
379 + ".jalview_properties";
383 // don't corrupt the file we've been given.
384 propsAreReadOnly = true;
387 if (propertiesFile == null)
389 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
390 applicationProperties);
399 fis = new URL(propertiesFile).openStream();
401 "Loading jalview properties from : " + propertiesFile);
403 "Disabling Jalview writing to user's local properties file.");
404 propsAreReadOnly = true;
406 } catch (Exception ex)
412 fis = new FileInputStream(propertiesFile);
414 applicationProperties.clear();
415 applicationProperties.load(fis);
417 // remove any old build properties
419 deleteBuildProperties();
421 } catch (Exception ex)
423 System.out.println("Error reading properties file: " + ex);
427 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
428 if (getDefault("USE_PROXY", false))
430 String proxyServer = getDefault("PROXY_SERVER", ""),
431 proxyPort = getDefault("PROXY_PORT", "8080");
435 // PROXY TYPE settings (now three options "none", "false", "true", but using
436 // backward compatible strings)
437 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
438 // default to upgrading old settings
442 clearProxyProperties();
444 case PROXYTYPE_SYSTEM: // use system settings
445 resetProxyProperties();
447 case PROXYTYPE_CUSTOM: // use specified proxy settings
448 String httpHost = getDefault("PROXY_SERVER", "");
449 String httpPort = getDefault("PROXY_PORT", "8080");
450 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
451 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
452 String httpUser = getDefault("PROXY_AUTH_USER", null);
453 // https.proxyUser and https.proxyPassword are not able to be
454 // independently set in Preferences yet (or http.nonProxyHosts)
455 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
456 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
457 proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
460 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
465 // LOAD THE AUTHORS FROM THE authors.props file
466 String authorDetails = resolveResourceURLFor("/authors.props");
470 if (authorDetails != null)
472 URL localJarFileURL = new URL(authorDetails);
473 InputStream in = localJarFileURL.openStream();
474 applicationProperties.load(in);
477 } catch (Exception ex)
479 System.out.println("Error reading author details: " + ex);
480 authorDetails = null;
482 if (authorDetails == null)
484 applicationProperties.remove("AUTHORS");
485 applicationProperties.remove("AUTHORFNAMES");
486 applicationProperties.remove("YEAR");
489 loadBuildProperties(false);
492 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
494 SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
495 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
497 SiftsSettings.setFailSafePIDThreshold(
498 jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
499 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
501 SiftsSettings.setCacheThresholdInDays(
502 jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
503 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
505 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
506 "http://www.jalview.org/services/identifiers"));
507 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
509 StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
510 .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
511 StructureImportSettings
512 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
513 // StructureImportSettings
514 // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
515 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
517 String jnlpVersion = System.getProperty("jalview.version");
519 // jnlpVersion will be null if a latest version check for the channel needs
521 // Dont do this check if running in headless mode
523 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
524 && (System.getProperty("java.awt.headless") == null || System
525 .getProperty("java.awt.headless").equals("false")))
528 class VersionChecker extends Thread
533 String orgtimeout = System
534 .getProperty("sun.net.client.defaultConnectTimeout");
535 if (orgtimeout == null)
538 System.out.println("# INFO: Setting default net timeout to "
539 + orgtimeout + " seconds.");
541 String remoteVersion = null;
544 System.setProperty("sun.net.client.defaultConnectTimeout",
546 java.net.URL url = new java.net.URL(Cache
547 .getDefault("www.jalview.org", "http://www.jalview.org")
548 + "/webstart/jalview.jnlp");
549 BufferedReader in = new BufferedReader(
550 new InputStreamReader(url.openStream()));
552 while ((line = in.readLine()) != null)
554 if (line.indexOf("jalview.version") == -1)
559 line = line.substring(line.indexOf("value=") + 7);
560 line = line.substring(0, line.lastIndexOf("\""));
561 remoteVersion = line;
564 } catch (Exception ex)
567 "Non-fatal exception when checking version at www.jalview.org :");
568 System.out.println(ex);
569 remoteVersion = getProperty("VERSION");
571 System.setProperty("sun.net.client.defaultConnectTimeout",
574 setProperty("LATEST_VERSION", remoteVersion);
578 VersionChecker vc = new VersionChecker();
583 if (jnlpVersion != null)
585 setProperty("LATEST_VERSION", jnlpVersion);
589 applicationProperties.remove("LATEST_VERSION");
593 // LOAD USERDEFINED COLOURS
594 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
595 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
600 * construct a resource URL for the given absolute resource pathname
602 * @param resourcePath
605 private static String resolveResourceURLFor(String resourcePath)
608 if (Platform.isJS() || !Cache.class.getProtectionDomain()
609 .getCodeSource().getLocation().toString().endsWith(".jar"))
613 url = Cache.class.getResource(resourcePath).toString();
614 } catch (Exception ex)
616 System.err.println("Failed to resolve resource " + resourcePath
617 + ": " + ex.getMessage());
622 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
623 .getLocation().toString().concat("!" + resourcePath));
628 public static void loadBuildProperties(boolean reportVersion)
630 String codeInstallation = getProperty("INSTALLATION");
631 boolean printVersion = codeInstallation == null;
634 * read build properties - from the Jalview jar for a Java distribution,
635 * or from codebase file in test or JalviewJS context
639 String buildDetails = resolveResourceURLFor("/.build_properties");
640 URL localJarFileURL = new URL(buildDetails);
641 InputStream in = localJarFileURL.openStream();
642 applicationProperties.load(in);
644 } catch (Exception ex)
646 System.out.println("Error reading build details: " + ex);
647 applicationProperties.remove("VERSION");
649 String codeVersion = getProperty("VERSION");
650 codeInstallation = getProperty("INSTALLATION");
652 if (codeVersion == null)
654 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
655 codeVersion = "Test";
656 codeInstallation = "";
660 codeInstallation = " (" + codeInstallation + ")";
662 setProperty("VERSION", codeVersion);
663 new BuildDetails(codeVersion, null, codeInstallation);
664 if (printVersion && reportVersion)
666 System.out.println(ChannelProperties.getProperty("app_name")
667 + " Version: " + codeVersion + codeInstallation);
671 private static void deleteBuildProperties()
673 applicationProperties.remove("LATEST_VERSION");
674 applicationProperties.remove("VERSION");
675 applicationProperties.remove("AUTHORS");
676 applicationProperties.remove("AUTHORFNAMES");
677 applicationProperties.remove("YEAR");
678 applicationProperties.remove("BUILD_DATE");
679 applicationProperties.remove("INSTALLATION");
683 * Gets Jalview application property of given key. Returns null if key not
689 * @return Property value
691 public static String getProperty(String key)
693 String prop = applicationProperties.getProperty(key);
694 if (prop == null && Platform.isJS())
696 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
697 + "_" + JS_PROPERTY_PREFIX + key);
703 * These methods are used when checking if the saved preference is different
704 * to the default setting
707 public static boolean getDefault(String property, boolean def)
709 String string = getProperty(property);
712 def = Boolean.valueOf(string).booleanValue();
718 public static int getDefault(String property, int def)
720 String string = getProperty(property);
725 def = Integer.parseInt(string);
726 } catch (NumberFormatException e)
728 System.out.println("Error parsing int property '" + property
729 + "' with value '" + string + "'");
737 * Answers the value of the given property, or the supplied default value if
738 * the property is not set
740 public static String getDefault(String property, String def)
742 String value = getProperty(property);
743 return value == null ? def : value;
747 * Stores property in the file "HOME_DIR/.jalview_properties"
752 * String value of property
754 * @return previous value of property (or null)
756 public static Object setProperty(String key, String obj)
758 Object oldValue = null;
761 oldValue = applicationProperties.setProperty(key, obj);
762 if (propertiesFile != null && !propsAreReadOnly)
764 FileOutputStream out = new FileOutputStream(propertiesFile);
765 applicationProperties.store(out, "---JalviewX Properties File---");
768 } catch (Exception ex)
771 "Error setting property: " + key + " " + obj + "\n" + ex);
777 * remove the specified property from the jalview properties file
781 public static void removeProperty(String string)
783 applicationProperties.remove(string);
788 * save the properties to the jalview properties path
790 public static void saveProperties()
792 if (!propsAreReadOnly)
796 FileOutputStream out = new FileOutputStream(propertiesFile);
797 applicationProperties.store(out, "---JalviewX Properties File---");
799 } catch (Exception ex)
801 System.out.println("Error saving properties: " + ex);
807 * internal vamsas class discovery state
809 private static int vamsasJarsArePresent = -1;
812 * Searches for vamsas client classes on class path.
814 * @return true if vamsas client is present on classpath
816 public static boolean vamsasJarsPresent()
818 if (vamsasJarsArePresent == -1)
822 if (jalview.jbgui.GDesktop.class.getClassLoader()
823 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
825 jalview.bin.Cache.log.debug(
826 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
827 vamsasJarsArePresent = 1;
828 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
829 lvclient.setLevel(Level.toLevel(Cache
830 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
832 lvclient.addAppender(log.getAppender("JalviewLogger"));
833 // Tell the user that debug is enabled
834 lvclient.debug(ChannelProperties.getProperty("app_name")
835 + " Vamsas Client Debugging Output Follows.");
837 } catch (Exception e)
839 vamsasJarsArePresent = 0;
840 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
843 return (vamsasJarsArePresent > 0);
847 * internal vamsas class discovery state
849 private static int groovyJarsArePresent = -1;
852 * Searches for vamsas client classes on class path.
854 * @return true if vamsas client is present on classpath
856 public static boolean groovyJarsPresent()
858 if (groovyJarsArePresent == -1)
862 if (Cache.class.getClassLoader()
863 .loadClass("groovy.lang.GroovyObject") != null)
865 jalview.bin.Cache.log.debug(
866 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
867 groovyJarsArePresent = 1;
868 Logger lgclient = Logger.getLogger("groovy");
869 lgclient.setLevel(Level.toLevel(Cache
870 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
872 lgclient.addAppender(log.getAppender("JalviewLogger"));
873 // Tell the user that debug is enabled
874 lgclient.debug(ChannelProperties.getProperty("app_name")
875 + " Groovy Client Debugging Output Follows.");
879 groovyJarsArePresent = 0;
880 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
881 } catch (Exception e)
883 groovyJarsArePresent = 0;
884 jalview.bin.Cache.log.debug("Groovy Classes are not present");
887 return (groovyJarsArePresent > 0);
891 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
894 protected static Object tracker = null;
896 protected static Class trackerfocus = null;
898 protected static Class jgoogleanalyticstracker = null;
901 * Initialise the google tracker if it is not done already.
903 public static void initGoogleTracker()
907 if (jgoogleanalyticstracker == null)
909 // try to get the tracker class
912 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
913 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
914 trackerfocus = Cache.class.getClassLoader()
915 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
916 } catch (Exception e)
919 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
921 jgoogleanalyticstracker = null;
926 // now initialise tracker
927 Exception re = null, ex = null;
929 String vrs = "No Version Accessible";
932 // Google analytics tracking code for Library Finder
933 tracker = jgoogleanalyticstracker
934 .getConstructor(new Class[]
935 { String.class, String.class, String.class })
936 .newInstance(new Object[]
937 { ChannelProperties.getProperty("app_name") + " Desktop",
938 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
939 + jalview.bin.Cache.getDefault("BUILD_DATE",
942 jgoogleanalyticstracker
943 .getMethod("trackAsynchronously", new Class[]
945 .invoke(tracker, new Object[]
946 { trackerfocus.getConstructor(new Class[] { String.class })
947 .newInstance(new Object[]
948 { "Application Started." }) });
949 } catch (RuntimeException e)
952 } catch (Exception e)
959 if (re != null || ex != null || err != null)
965 log.debug("Caught runtime exception in googletracker init:",
971 "Failed to initialise GoogleTracker for Jalview Desktop with version "
978 "Whilst initing GoogleTracker for Jalview Desktop version "
988 "Debug: Caught runtime exception in googletracker init:"
990 re.printStackTrace();
995 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
997 ex.printStackTrace();
1003 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1005 err.printStackTrace();
1011 log.debug("Successfully initialised tracker.");
1017 * get the user's default colour if available
1023 public static Color getDefaultColour(String property, Color defcolour)
1025 String colprop = getProperty(property);
1026 if (colprop == null)
1030 Color col = ColorUtils.parseColourString(colprop);
1033 log.warn("Couldn't parse '" + colprop + "' as a colour for "
1036 return (col == null) ? defcolour : col;
1040 * store a colour as a Jalview user default property
1045 public static void setColourProperty(String property, Color colour)
1047 setProperty(property, jalview.util.Format.getHexString(colour));
1051 * Stores a formatted date in a jalview property, using a fixed locale.
1053 * @param propertyName
1055 * @return the formatted date string
1057 public static String setDateProperty(String propertyName, Date date)
1059 String formatted = date_format.format(date);
1060 setProperty(propertyName, formatted);
1065 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1066 * format) and returns as a Date, or null if parsing fails
1068 * @param propertyName
1072 public static Date getDateProperty(String propertyName)
1074 String val = getProperty(propertyName);
1079 return date_format.parse(val);
1080 } catch (Exception ex)
1082 System.err.println("Invalid or corrupt date in property '"
1083 + propertyName + "' : value was '" + val + "'");
1090 * get and parse a property as an integer. send any parsing problems to
1094 * @return null or Integer
1096 public static Integer getIntegerProperty(String property)
1098 String val = getProperty(property);
1099 if (val != null && (val = val.trim()).length() > 0)
1103 return Integer.valueOf(val);
1104 } catch (NumberFormatException x)
1106 System.err.println("Invalid integer in property '" + property
1107 + "' (value was '" + val + "')");
1114 * Set the specified value, or remove it if null or empty. Does not save the
1120 public static void setOrRemove(String propName, String value)
1122 if (propName == null)
1126 if (value == null || value.trim().length() < 1)
1128 Cache.applicationProperties.remove(propName);
1132 Cache.applicationProperties.setProperty(propName, value);
1137 * Loads in user colour schemes from files.
1140 * a '|'-delimited list of file paths
1142 public static void initUserColourSchemes(String files)
1144 if (files == null || files.length() == 0)
1149 // In case colours can't be loaded, we'll remove them
1150 // from the default list here.
1151 StringBuffer coloursFound = new StringBuffer();
1152 StringTokenizer st = new StringTokenizer(files, "|");
1153 while (st.hasMoreElements())
1155 String file = st.nextToken();
1158 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1161 if (coloursFound.length() > 0)
1163 coloursFound.append("|");
1165 coloursFound.append(file);
1166 ColourSchemes.getInstance().registerColourScheme(ucs);
1168 } catch (Exception ex)
1170 System.out.println("Error loading User ColourFile\n" + ex);
1173 if (!files.equals(coloursFound.toString()))
1175 if (coloursFound.toString().length() > 1)
1177 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1178 coloursFound.toString());
1182 applicationProperties
1183 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1189 * Initial logging information helper for various versions output
1193 * @param defaultValue
1195 private static void appendIfNotNull(StringBuilder sb, String prefix,
1196 String value, String suffix, String defaultValue)
1198 if (value == null && defaultValue == null)
1202 String line = prefix + (value != null ? value : defaultValue) + suffix;
1208 * @return Jalview version, build details and JVM platform version for console
1210 public static String getVersionDetailsForConsole()
1212 StringBuilder sb = new StringBuilder();
1213 sb.append(ChannelProperties.getProperty("app_name"))
1214 .append(" Version: ");
1215 sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1217 sb.append(ChannelProperties.getProperty("app_name"))
1218 .append(" Installation: ");
1219 sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1221 sb.append("Build Date: ");
1222 sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1224 sb.append("Java version: ");
1225 sb.append(System.getProperty("java.version"));
1227 sb.append(System.getProperty("os.arch"));
1229 sb.append(System.getProperty("os.name"));
1231 sb.append(System.getProperty("os.version"));
1233 appendIfNotNull(sb, "Install4j version: ",
1234 System.getProperty("sys.install4jVersion"), "\n", null);
1235 appendIfNotNull(sb, "Install4j template version: ",
1236 System.getProperty("installer_template_version"), "\n", null);
1237 appendIfNotNull(sb, "Launcher version: ",
1238 System.getProperty("launcher_version"), "\n", null);
1239 LookAndFeel laf = UIManager.getLookAndFeel();
1240 String lafName = laf == null ? "Not obtained" : laf.getName();
1241 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1242 sb.append("LookAndFeel: ");
1245 sb.append(lafClass);
1247 // Not displayed in release version ( determined by possible version number
1248 // regex 9[9.]*9[.-_a9]* )
1249 if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1250 jalview.bin.Cache.getDefault("VERSION", "TEST")))
1252 appendIfNotNull(sb, "Getdown appdir: ",
1253 System.getProperty("getdownappdir"), "\n", null);
1254 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1257 return sb.toString();
1262 * @return build details as reported in splashscreen
1264 public static String getBuildDetailsForSplash()
1266 // consider returning more human friendly info
1267 // eg 'built from Source' or update channel
1268 return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1271 public static String getStackTraceString(Throwable t)
1273 StringWriter sw = new StringWriter();
1274 PrintWriter pw = new PrintWriter(sw);
1275 t.printStackTrace(pw);
1276 return sw.toString();
1279 // proxy properties methods
1280 public static void clearProxyProperties()
1282 setProxyProperties(null, null, null, null, null, null, null, null,
1286 public static void resetProxyProperties()
1288 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1289 startupProxyProperties[2], startupProxyProperties[3],
1290 startupProxyProperties[4],
1291 startupProxyProperties[5] == null ? null
1292 : startupProxyProperties[5].toCharArray(),
1293 startupProxyProperties[6],
1294 startupProxyProperties[7] == null ? null
1295 : startupProxyProperties[7].toCharArray(),
1296 startupProxyProperties[8]);
1297 StringBuilder sb = new StringBuilder();
1298 sb.append("Setting proxy properties to: http.proxyHost=")
1299 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1300 .append(startupProxyProperties[1])
1301 .append(startupProxyProperties[4] != null
1302 && !startupProxyProperties[4].isEmpty()
1303 ? " [" + startupProxyProperties[4] + "]"
1305 .append(", https.proxyHost=").append(startupProxyProperties[2])
1306 .append(", https.proxyPort=").append(startupProxyProperties[3])
1307 .append(startupProxyProperties[6] != null
1308 && !startupProxyProperties[6].isEmpty()
1309 ? " [" + startupProxyProperties[6] + "]"
1312 Cache.debug(sb.toString());
1315 public static void setProxyPropertiesFromPreferences()
1317 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1320 public static void setProxyPropertiesFromPreferences(
1321 String previousProxyType)
1323 String proxyType = Cache.getDefault("USE_PROXY",
1324 Cache.PROXYTYPE_SYSTEM);
1325 if (previousProxyType != null
1326 && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1328 && proxyType.equals(previousProxyType))
1335 case Cache.PROXYTYPE_NONE:
1336 if (!previousProxyType.equals(proxyType))
1338 Cache.log.info("Setting no proxy settings");
1339 Cache.setProxyProperties(null, null, null, null, null, null, null,
1343 case Cache.PROXYTYPE_CUSTOM:
1344 // always re-set a custom proxy -- it might have changed, particularly
1346 Cache.log.info("Setting custom proxy settings");
1347 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1348 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1349 Cache.getDefault("PROXY_PORT", null),
1350 Cache.getDefault("PROXY_SERVER_HTTPS", null),
1351 Cache.getDefault("PROXY_PORT_HTTPS", null),
1352 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1354 proxyAuthSet ? Cache.proxyAuthPassword : null,
1355 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1357 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1359 default: // system proxy settings by default
1360 Cache.log.info("Setting system proxy settings");
1361 Cache.resetProxyProperties();
1365 public static void setProxyProperties(String httpHost, String httpPort,
1366 String httpsHost, String httpsPort, String httpUser,
1367 char[] httpPassword, String httpsUser, char[] httpsPassword,
1368 String nonProxyHosts)
1370 setOrClearSystemProperty("http.proxyHost", httpHost);
1371 setOrClearSystemProperty("http.proxyPort", httpPort);
1372 setOrClearSystemProperty("https.proxyHost", httpsHost);
1373 setOrClearSystemProperty("https.proxyPort", httpsPort);
1374 setOrClearSystemProperty("http.proxyUser", httpUser);
1375 setOrClearSystemProperty("https.proxyUser", httpsUser);
1376 // note: passwords for http.proxyPassword and https.proxyPassword are sent
1377 // via the Authenticator, properties do not need to be set
1379 // are we using a custom proxy (password prompt might be required)?
1380 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1381 .equals(PROXYTYPE_CUSTOM);
1384 * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1385 * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1386 * is not re-called).
1387 * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1389 * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1391 * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1396 sun.net.www.protocol.http.AuthCacheValue
1397 .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1398 } catch (Throwable t)
1400 Cache.error(t.getMessage());
1401 Cache.debug(getStackTraceString(t));
1405 if (httpUser != null || httpsUser != null)
1409 char[] displayHttpPw = new char[httpPassword == null ? 0
1410 : httpPassword.length];
1411 Arrays.fill(displayHttpPw, '*');
1412 Cache.debug("CACHE Proxy: setting new Authenticator with httpUser='"
1413 + httpUser + "' httpPassword='" + displayHttpPw + "'");
1414 Authenticator.setDefault(new Authenticator()
1417 protected PasswordAuthentication getPasswordAuthentication()
1419 if (getRequestorType() == RequestorType.PROXY)
1421 String protocol = getRequestingProtocol();
1422 boolean needProxyPasswordSet = false;
1423 if (customProxySet &&
1424 // we have a username but no password for the scheme being
1426 (protocol.equalsIgnoreCase("http")
1427 && (httpUser != null && httpUser.length() > 0
1428 && (httpPassword == null
1429 || httpPassword.length == 0)))
1430 || (protocol.equalsIgnoreCase("https")
1431 && (httpsUser != null
1432 && httpsUser.length() > 0
1433 && (httpsPassword == null
1434 || httpsPassword.length == 0))))
1436 // open Preferences -> Connections
1437 String message = MessageManager
1438 .getString("label.proxy_password_required");
1439 Preferences.openPreferences(Preferences.CONNECTIONS_TAB,
1441 Preferences.getInstance()
1442 .proxyAuthPasswordCheckHighlight(true, true);
1448 if (protocol.equalsIgnoreCase("http")
1449 && getRequestingHost().equalsIgnoreCase(httpHost)
1450 && getRequestingPort() == Integer
1454 "AUTHENTICATOR returning PasswordAuthentication(\""
1455 + httpUser + "\", '"
1456 + new String(displayHttpPw) + "')");
1457 return new PasswordAuthentication(httpUser,
1460 if (protocol.equalsIgnoreCase("https")
1461 && getRequestingHost().equalsIgnoreCase(httpsHost)
1462 && getRequestingPort() == Integer
1463 .valueOf(httpsPort))
1465 char[] displayHttpsPw = new char[httpPassword.length];
1466 Arrays.fill(displayHttpsPw, '*');
1468 "AUTHENTICATOR returning PasswordAuthentication(\""
1469 + httpsUser + "\", '" + displayHttpsPw
1471 return new PasswordAuthentication(httpsUser,
1474 } catch (NumberFormatException e)
1476 Cache.error("Problem with proxy port values [http:"
1477 + httpPort + ", https:" + httpsPort + "]");
1480 "AUTHENTICATOR after trying to get PasswordAuthentication");
1483 // non proxy request
1484 Cache.debug("AUTHENTICATOR returning null");
1488 // required to re-enable basic authentication (should be okay for a
1491 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1492 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1493 } catch (SecurityException e)
1495 Cache.error("Could not set default Authenticator");
1496 Cache.debug(getStackTraceString(e));
1501 // reset the Authenticator to protect http.proxyUser and
1502 // http.proxyPassword Just In Case
1503 /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1504 * has working credentials. No workaround for Java 11.
1506 Cache.debug("AUTHENTICATOR setting default Authenticator to null");
1507 Authenticator.setDefault(null);
1510 // nonProxyHosts not currently configurable in Preferences
1511 Cache.debug("AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1512 + nonProxyHosts + "\"");
1513 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1516 public static void setOrClearSystemProperty(String key, char[] value)
1518 setOrClearSystemProperty(key,
1519 (value == null) ? null : new String(value));
1522 public static void setOrClearSystemProperty(String key, String value)
1530 System.clearProperty(key);
1534 System.setProperty(key, value);
1538 public final static int TRACE = 10;
1540 public final static int DEBUG = 20;
1542 public final static int INFO = 30;
1544 public final static int WARN = 40;
1546 public final static int ERROR = 50;
1548 public static boolean println(int level, String message)
1550 if (Cache.log == null)
1553 System.err.println(message);
1554 else if (level >= INFO)
1555 System.out.println(message);
1556 // not printing debug or trace messages
1561 Cache.log.error(message);
1563 else if (level >= WARN)
1565 Cache.log.warn(message);
1567 else if (level >= INFO)
1569 Cache.log.info(message);
1571 else if (level >= DEBUG)
1573 Cache.log.debug(message);
1577 Cache.log.trace(message);
1582 public static void trace(String message)
1584 println(TRACE, message);
1587 public static void debug(String message)
1589 println(DEBUG, message);
1592 public static void info(String message)
1594 println(INFO, message);
1597 public static void warn(String message)
1599 println(WARN, message);
1602 public static void error(String message)
1604 println(ERROR, message);