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;
46 import javax.swing.LookAndFeel;
47 import javax.swing.UIManager;
49 import jalview.datamodel.PDBEntry;
50 import jalview.gui.Preferences;
51 import jalview.gui.UserDefinedColours;
52 import jalview.log.JLoggerLog4j;
53 import jalview.schemes.ColourSchemeLoader;
54 import jalview.schemes.ColourSchemes;
55 import jalview.schemes.UserColourScheme;
56 import jalview.structure.StructureImportSettings;
57 import jalview.urls.IdOrgSettings;
58 import jalview.util.ChannelProperties;
59 import jalview.util.ColorUtils;
60 import jalview.util.MessageManager;
61 import jalview.util.Platform;
62 import jalview.ws.sifts.SiftsSettings;
65 * Stores and retrieves Jalview Application Properties Lists and fields within
66 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
67 * are alternative values for a tag. <br>
69 * Current properties include:
72 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
73 * logging level for axis (used for web services) <br>
75 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
76 * the logging level for castor (used for serialization) <br>
78 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
80 * <li>SCREEN_WIDTH</li>
81 * <li>SCREEN_HEIGHT</li>
82 * <li>SCREEN_Y=285</li>
83 * <li>SCREEN_X=371</li>
84 * <li>SHOW_FULLSCREEN boolean</li>
85 * <li>FONT_NAME java font name for alignment text display</li>
86 * <li>FONT_SIZE size of displayed alignment text</li>
87 * <li>FONT_STYLE style of font displayed (sequence labels are always
89 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
90 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
91 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
92 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
93 * <li>SHOW_IDENTITY show percentage identity annotation</li>
94 * <li>SHOW_QUALITY show alignment quality annotation</li>
95 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
96 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
97 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
98 * LABEL_AND_SEQUENCE</li>
99 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
100 * sequence annotations</li>
101 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
102 * annotation row</li>
103 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
104 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
105 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
106 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
107 * <li>VERSION the version of the jalview build</li>
108 * <li>BUILD_DATE date of this build</li>
109 * <li>LATEST_VERSION the latest jalview version advertised on the
110 * www.jalview.org</li>
111 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
113 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
114 * suffix to file</li>
115 * <li>RECENT_URL list of recently retrieved URLs</li>
116 * <li>RECENT_FILE list of recently opened files</li>
117 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
118 * <li>PROXY_SERVER the proxy</li>
119 * <li>PROXY_PORT</li>
120 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
122 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
124 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
125 * collecting usage statistics</li>
126 * <li>SHOW_OVERVIEW boolean for overview window display</li>
127 * <li>ANTI_ALIAS boolean for smooth fonts</li>
128 * <li>RIGHT_ALIGN_IDS boolean</li>
129 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
130 * <li>PAD_GAPS boolean</li>
131 * <li>ID_ITALICS boolean</li>
132 * <li>SHOW_JV_SUFFIX</li>
133 * <li>WRAP_ALIGNMENT</li>
134 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
136 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
137 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
139 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
141 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
142 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
143 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
144 * jalview.utils.GroupURLLink for more info</li>
145 * <li>DEFAULT_BROWSER for unix</li>
146 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
148 * <li>VERSION_CHECK (true) check for the latest release version from
149 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
150 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
152 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
154 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
155 * displayed as '.'</li>
156 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
157 * order of a newly displayed tree</li>
158 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
159 * sequence ID strings before attempting retrieval from any datasource</li>
160 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
162 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
163 * in the alignment.</li>
164 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
166 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
168 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
169 * logo normalised to row height rather than histogram height.</li>
170 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
171 * respond to selections made in other alignments containing the same sequences.
173 * <li>SHOW_JWS2_SERVICES (true) when set to false, jalview will not
174 * auto-discover JABAWS services</li>
175 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
176 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
177 * warning dialog box is displayed.</li>
178 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
179 * when shading by annotation</li>
180 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
181 * when shading by annotation</li>
182 * <li>www.jalview.org (https://www.jalview.org) a property enabling all HTTP
183 * requests to be redirected to a mirror of https://www.jalview.org</li>
184 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
185 * alignment figure to accommodate even the longest sequence ID or annotation
187 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
188 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
189 * will override this).</li>
190 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
192 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
193 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
195 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
197 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
199 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
200 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
202 * <li>NONEWS - when set disables Jalview News from automatically appearing</li>
203 * <li>NOHTMLTEMPLATES - when set, the
204 * https://github.com/jalview/exporter-templates/tree/master/biojs repository is
205 * not downloaded automatically</li>
206 * <li>NOIDENTIFIERSSERVICE - when set, jalview won't automatically download
207 * available URL linkouts via www.jalview.org/services/identifiers</li>
210 * Deprecated settings:
213 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
214 * startup (JWS1 services only)</li>
215 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
216 * (JWS1 services only)</li>
217 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
218 * services in the desktop GUI</li>
219 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
220 * panel in web service preferences</li>
224 * @version $Revision$
229 * property giving log4j level for CASTOR loggers
231 public static final String CASTORLOGLEVEL = "logs.Castor.level";
234 * property giving log4j level for AXIS loggers
236 public static final String AXISLOGLEVEL = "logs.Axis.level";
239 * property giving log4j level for Jalview Log
241 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
246 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
247 .getProperty("user.home") + File.separatorChar
248 + ".sifts_downloads" + File.separatorChar;
250 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
252 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
255 * Identifiers.org download settings
257 private static final String ID_ORG_FILE = System.getProperty("user.home")
258 + File.separatorChar + ".identifiers.org.ids.json";
261 * Allowed values are PDB or mmCIF
263 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
266 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
270 * a date formatter using a fixed (rather than the user's) locale;
271 * this ensures that date properties can be written and re-read successfully
272 * even if the user changes their locale setting
274 private static final DateFormat date_format = SimpleDateFormat
275 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
276 SimpleDateFormat.MEDIUM, Locale.UK);
279 * Initialises the Jalview Application Log
282 public final static String JALVIEW_LOGGER_NAME = "JalviewLogger";
284 // save the proxy properties set at startup
285 public final static String[] startupProxyProperties = {
286 System.getProperty("http.proxyHost"),
287 System.getProperty("http.proxyPort"),
288 System.getProperty("https.proxyHost"),
289 System.getProperty("https.proxyPort"),
290 System.getProperty("http.proxyUser"),
291 System.getProperty("http.proxyPassword"),
292 System.getProperty("https.proxyUser"),
293 System.getProperty("https.proxyPassword"),
294 System.getProperty("http.nonProxyHosts") };
296 public final static String PROXYTYPE_NONE = "none";
298 // "false" and "true" for backward compatibility
299 public final static String PROXYTYPE_SYSTEM = "false";
301 public final static String PROXYTYPE_CUSTOM = "true";
303 // in-memory only storage of proxy password, safer to use char array
304 public static char[] proxyAuthPassword = null;
306 /** Jalview Properties */
307 public static Properties applicationProperties = new Properties()
309 // override results in properties output in alphabetical order
311 public synchronized Enumeration<Object> keys()
313 return Collections.enumeration(new TreeSet<>(super.keySet()));
317 /* build Properties (not all saved to .jalview_properties) */
318 public static Properties buildProperties = new Properties();
320 /** Default file is ~/.jalview_properties */
321 static String propertiesFile;
323 private static boolean propsAreReadOnly = Platform.isJS();
325 private final static String JS_PROPERTY_PREFIX = "jalview_";
328 * Loads properties from the given properties file. Any existing properties
331 public static void loadProperties(String propsFile)
333 propertiesFile = propsFile;
334 String releasePropertiesFile = null;
335 boolean defaultProperties = false;
336 if (propsFile == null && !propsAreReadOnly)
338 String channelPrefsFilename = ChannelProperties
339 .getProperty("preferences.filename");
340 String releasePrefsFilename = ".jalview_properties";
341 propertiesFile = System.getProperty("user.home") + File.separatorChar
342 + channelPrefsFilename;
343 releasePropertiesFile = System.getProperty("user.home")
344 + File.separatorChar + releasePrefsFilename;
345 defaultProperties = true;
349 // don't corrupt the file we've been given.
350 propsAreReadOnly = true;
353 if (propertiesFile == null)
355 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
356 applicationProperties);
365 // props file provided as URL
366 fis = new URL(propertiesFile).openStream();
368 "Loading jalview properties from : " + propertiesFile);
370 "Disabling Jalview writing to user's local properties file.");
371 propsAreReadOnly = true;
372 } catch (Exception ex)
378 String readPropertiesFile = propertiesFile;
379 // if we're using the usual properties file and the channel properties
380 // file doesn't exist, read .jalview_properties
381 // (but we'll still save to the channel properties file).
382 if (defaultProperties && (!new File(propertiesFile).exists())
383 && (new File(releasePropertiesFile).exists()))
385 readPropertiesFile = releasePropertiesFile;
387 fis = new FileInputStream(readPropertiesFile);
389 applicationProperties.clear();
390 applicationProperties.load(fis);
392 // remove any old build properties
394 deleteBuildProperties();
396 } catch (Exception ex)
398 System.out.println("Error reading properties file: " + ex);
402 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
403 if (getDefault("USE_PROXY", false))
405 String proxyServer = getDefault("PROXY_SERVER", ""),
406 proxyPort = getDefault("PROXY_PORT", "8080");
410 // PROXY TYPE settings (now three options "none", "false", "true", but using
411 // backward compatible strings)
412 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
413 // default to upgrading old settings
417 clearProxyProperties();
419 case PROXYTYPE_SYSTEM: // use system settings
420 resetProxyProperties();
422 case PROXYTYPE_CUSTOM: // use specified proxy settings
423 String httpHost = getDefault("PROXY_SERVER", "");
424 String httpPort = getDefault("PROXY_PORT", "8080");
425 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
426 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
427 String httpUser = getDefault("PROXY_AUTH_USER", null);
428 // https.proxyUser and https.proxyPassword are not able to be
429 // independently set in Preferences yet (or http.nonProxyHosts)
430 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
431 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
432 proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
435 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
437 Console.warn(message);
440 // LOAD THE AUTHORS FROM THE authors.props file
441 String authorDetails = resolveResourceURLFor("/authors.props");
445 if (authorDetails != null)
447 URL localJarFileURL = new URL(authorDetails);
448 InputStream in = localJarFileURL.openStream();
449 applicationProperties.load(in);
452 } catch (Exception ex)
454 System.out.println("Error reading author details: " + ex);
455 authorDetails = null;
457 if (authorDetails == null)
459 applicationProperties.remove("AUTHORS");
460 applicationProperties.remove("AUTHORFNAMES");
461 applicationProperties.remove("YEAR");
464 loadBuildProperties(false);
467 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
469 SiftsSettings.setSiftDownloadDirectory(Cache
470 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
472 SiftsSettings.setFailSafePIDThreshold(
473 Cache.getDefault("sifts_fail_safe_pid_threshold",
474 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
476 SiftsSettings.setCacheThresholdInDays(
477 Cache.getDefault("sifts_cache_threshold_in_days",
478 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
480 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
481 "https://www.jalview.org/services/identifiers"));
482 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
484 StructureImportSettings.setDefaultStructureFileFormat(
485 Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
486 StructureImportSettings
487 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
488 // StructureImportSettings
489 // .setDefaultPDBFileParser(Cache.getDefault(
490 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
492 String jnlpVersion = System.getProperty("jalview.version");
494 // jnlpVersion will be null if a latest version check for the channel needs
496 // Dont do this check if running in headless mode
498 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
499 && (System.getProperty("java.awt.headless") == null || System
500 .getProperty("java.awt.headless").equals("false")))
503 class VersionChecker extends Thread
509 String remoteBuildPropertiesUrl = Cache
510 .getAppbaseBuildProperties();
512 String orgtimeout = System
513 .getProperty("sun.net.client.defaultConnectTimeout");
514 if (orgtimeout == null)
517 System.out.println("# INFO: Setting default net timeout to "
518 + orgtimeout + " seconds.");
520 String remoteVersion = null;
521 if (remoteBuildPropertiesUrl.startsWith("http"))
525 System.setProperty("sun.net.client.defaultConnectTimeout",
528 URL url = new URL(remoteBuildPropertiesUrl);
530 BufferedReader in = new BufferedReader(
531 new InputStreamReader(url.openStream()));
533 Properties remoteBuildProperties = new Properties();
534 remoteBuildProperties.load(in);
535 remoteVersion = remoteBuildProperties.getProperty("VERSION");
536 } catch (Exception ex)
539 "Non-fatal exception when checking version at "
540 + remoteBuildPropertiesUrl + ":");
541 System.out.println(ex);
542 remoteVersion = getProperty("VERSION");
545 System.setProperty("sun.net.client.defaultConnectTimeout",
548 setProperty("LATEST_VERSION", remoteVersion);
552 VersionChecker vc = new VersionChecker();
557 if (jnlpVersion != null)
559 setProperty("LATEST_VERSION", jnlpVersion);
563 applicationProperties.remove("LATEST_VERSION");
567 // LOAD USERDEFINED COLOURS
568 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
569 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
574 * construct a resource URL for the given absolute resource pathname
576 * @param resourcePath
579 private static String resolveResourceURLFor(String resourcePath)
582 if (Platform.isJS() || !Cache.class.getProtectionDomain()
583 .getCodeSource().getLocation().toString().endsWith(".jar"))
587 url = Cache.class.getResource(resourcePath).toString();
588 } catch (Exception ex)
590 System.err.println("Failed to resolve resource " + resourcePath
591 + ": " + ex.getMessage());
596 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
597 .getLocation().toString().concat("!" + resourcePath));
602 public static void loadBuildProperties(boolean reportVersion)
604 String codeInstallation = getProperty("INSTALLATION");
605 boolean printVersion = codeInstallation == null;
608 * read build properties - from the Jalview jar for a Java distribution,
609 * or from codebase file in test or JalviewJS context
613 String buildDetails = resolveResourceURLFor("/.build_properties");
614 URL localJarFileURL = new URL(buildDetails);
615 InputStream in = localJarFileURL.openStream();
616 buildProperties.load(in);
618 if (buildProperties.getProperty("BUILD_DATE", null) != null)
620 applicationProperties.put("BUILD_DATE",
621 buildProperties.getProperty("BUILD_DATE"));
623 if (buildProperties.getProperty("INSTALLATION", null) != null)
625 applicationProperties.put("INSTALLATION",
626 buildProperties.getProperty("INSTALLATION"));
628 if (buildProperties.getProperty("VERSION", null) != null)
630 applicationProperties.put("VERSION",
631 buildProperties.getProperty("VERSION"));
633 } catch (Exception ex)
635 System.out.println("Error reading build details: " + ex);
636 applicationProperties.remove("VERSION");
638 String codeVersion = getProperty("VERSION");
639 codeInstallation = getProperty("INSTALLATION");
641 if (codeVersion == null)
643 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
644 codeVersion = "Test";
645 codeInstallation = "";
649 codeInstallation = " (" + codeInstallation + ")";
651 setProperty("VERSION", codeVersion);
652 new BuildDetails(codeVersion, null, codeInstallation);
653 if (printVersion && reportVersion)
655 System.out.println(ChannelProperties.getProperty("app_name")
656 + " Version: " + codeVersion + codeInstallation);
660 private static void deleteBuildProperties()
662 applicationProperties.remove("LATEST_VERSION");
663 applicationProperties.remove("VERSION");
664 applicationProperties.remove("AUTHORS");
665 applicationProperties.remove("AUTHORFNAMES");
666 applicationProperties.remove("YEAR");
667 applicationProperties.remove("BUILD_DATE");
668 applicationProperties.remove("INSTALLATION");
672 * Gets Jalview application property of given key. Returns null if key not
678 * @return Property value
680 public static String getProperty(String key)
682 String prop = applicationProperties.getProperty(key);
683 if (prop == null && Platform.isJS())
685 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
686 + "_" + JS_PROPERTY_PREFIX + key);
692 * These methods are used when checking if the saved preference is different
693 * to the default setting
696 public static boolean getDefault(String property, boolean def)
698 String string = getProperty(property);
701 def = Boolean.valueOf(string).booleanValue();
707 public static int getDefault(String property, int def)
709 String string = getProperty(property);
714 def = Integer.parseInt(string);
715 } catch (NumberFormatException e)
717 System.out.println("Error parsing int property '" + property
718 + "' with value '" + string + "'");
726 * Answers the value of the given property, or the supplied default value if
727 * the property is not set
729 public static String getDefault(String property, String def)
731 String value = getProperty(property);
732 return value == null ? def : value;
736 * Stores property in the file "HOME_DIR/.jalview_properties"
741 * String value of property
743 * @return previous value of property (or null)
745 public static Object setProperty(String key, String obj)
747 Object oldValue = null;
750 oldValue = applicationProperties.setProperty(key, obj);
751 if (propertiesFile != null && !propsAreReadOnly)
753 FileOutputStream out = new FileOutputStream(propertiesFile);
754 applicationProperties.store(out, "---JalviewX Properties File---");
757 } catch (Exception ex)
760 "Error setting property: " + key + " " + obj + "\n" + ex);
766 * remove the specified property from the jalview properties file
770 public static void removeProperty(String string)
772 applicationProperties.remove(string);
777 * save the properties to the jalview properties path
779 public static void saveProperties()
781 if (!propsAreReadOnly)
785 FileOutputStream out = new FileOutputStream(propertiesFile);
786 applicationProperties.store(out, "---JalviewX Properties File---");
788 } catch (Exception ex)
790 System.out.println("Error saving properties: " + ex);
796 * internal vamsas class discovery state
798 private static int vamsasJarsArePresent = -1;
801 * Searches for vamsas client classes on class path.
803 * @return true if vamsas client is present on classpath
805 public static boolean vamsasJarsPresent()
807 if (vamsasJarsArePresent == -1)
811 if (jalview.jbgui.GDesktop.class.getClassLoader()
812 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
815 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
816 vamsasJarsArePresent = 1;
817 JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
818 Console.getCachedLogLevel("logs.Vamsas.Level"));
819 JLoggerLog4j.addAppender(lvclient, Console.log,
820 JALVIEW_LOGGER_NAME);
821 // Tell the user that debug is enabled
822 lvclient.debug(ChannelProperties.getProperty("app_name")
823 + " Vamsas Client Debugging Output Follows.");
825 } catch (Exception e)
827 vamsasJarsArePresent = 0;
828 Console.debug("Vamsas Classes are not present");
831 return (vamsasJarsArePresent > 0);
835 * internal vamsas class discovery state
837 private static int groovyJarsArePresent = -1;
840 * Searches for vamsas client classes on class path.
842 * @return true if vamsas client is present on classpath
844 public static boolean groovyJarsPresent()
846 if (groovyJarsArePresent == -1)
850 if (Cache.class.getClassLoader()
851 .loadClass("groovy.lang.GroovyObject") != null)
854 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
855 groovyJarsArePresent = 1;
856 JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
857 Console.getCachedLogLevel("logs.Groovy.Level"));
858 JLoggerLog4j.addAppender(lgclient, Console.log,
859 JALVIEW_LOGGER_NAME);
860 // Tell the user that debug is enabled
861 lgclient.debug(ChannelProperties.getProperty("app_name")
862 + " Groovy Client Debugging Output Follows.");
866 groovyJarsArePresent = 0;
867 Console.debug("Groovy Classes are not present", e);
868 } catch (Exception e)
870 groovyJarsArePresent = 0;
871 Console.debug("Groovy Classes are not present");
874 return (groovyJarsArePresent > 0);
878 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
881 protected static Object tracker = null;
883 protected static Class trackerfocus = null;
885 protected static Class jgoogleanalyticstracker = null;
888 * Initialise the google tracker if it is not done already.
890 public static void initGoogleTracker()
894 if (jgoogleanalyticstracker == null)
896 // try to get the tracker class
899 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
900 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
901 trackerfocus = Cache.class.getClassLoader()
902 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
903 } catch (Exception e)
906 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
908 jgoogleanalyticstracker = null;
913 // now initialise tracker
914 Exception re = null, ex = null;
916 String vrs = "No Version Accessible";
919 // Google analytics tracking code for Library Finder
920 tracker = jgoogleanalyticstracker
921 .getConstructor(new Class[]
922 { String.class, String.class, String.class })
923 .newInstance(new Object[]
924 { ChannelProperties.getProperty("app_name") + " Desktop",
925 (vrs = Cache.getProperty("VERSION") + "_"
926 + Cache.getDefault("BUILD_DATE", "unknown")),
928 jgoogleanalyticstracker
929 .getMethod("trackAsynchronously", new Class[]
931 .invoke(tracker, new Object[]
932 { trackerfocus.getConstructor(new Class[] { String.class })
933 .newInstance(new Object[]
934 { "Application Started." }) });
935 } catch (RuntimeException e)
938 } catch (Exception e)
945 if (re != null || ex != null || err != null)
949 Console.debug("Caught runtime exception in googletracker init:",
955 "Failed to initialise GoogleTracker for Jalview Desktop with version "
962 "Whilst initing GoogleTracker for Jalview Desktop version "
969 Console.debug("Successfully initialised tracker.");
975 * get the user's default colour if available
981 public static Color getDefaultColour(String property, Color defcolour)
983 String colprop = getProperty(property);
988 Color col = ColorUtils.parseColourString(colprop);
991 Console.warn("Couldn't parse '" + colprop + "' as a colour for "
994 return (col == null) ? defcolour : col;
998 * store a colour as a Jalview user default property
1003 public static void setColourProperty(String property, Color colour)
1005 setProperty(property, jalview.util.Format.getHexString(colour));
1009 * Stores a formatted date in a jalview property, using a fixed locale.
1011 * @param propertyName
1013 * @return the formatted date string
1015 public static String setDateProperty(String propertyName, Date date)
1017 String formatted = date_format.format(date);
1018 setProperty(propertyName, formatted);
1023 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1024 * format) and returns as a Date, or null if parsing fails
1026 * @param propertyName
1030 public static Date getDateProperty(String propertyName)
1032 String val = getProperty(propertyName);
1037 return date_format.parse(val);
1038 } catch (Exception ex)
1040 System.err.println("Invalid or corrupt date in property '"
1041 + propertyName + "' : value was '" + val + "'");
1048 * get and parse a property as an integer. send any parsing problems to
1052 * @return null or Integer
1054 public static Integer getIntegerProperty(String property)
1056 String val = getProperty(property);
1057 if (val != null && (val = val.trim()).length() > 0)
1061 return Integer.valueOf(val);
1062 } catch (NumberFormatException x)
1064 System.err.println("Invalid integer in property '" + property
1065 + "' (value was '" + val + "')");
1072 * Set the specified value, or remove it if null or empty. Does not save the
1078 public static void setOrRemove(String propName, String value)
1080 if (propName == null)
1084 if (value == null || value.trim().length() < 1)
1086 Cache.applicationProperties.remove(propName);
1090 Cache.applicationProperties.setProperty(propName, value);
1095 * Loads in user colour schemes from files.
1098 * a '|'-delimited list of file paths
1100 public static void initUserColourSchemes(String files)
1102 if (files == null || files.length() == 0)
1107 // In case colours can't be loaded, we'll remove them
1108 // from the default list here.
1109 StringBuffer coloursFound = new StringBuffer();
1110 StringTokenizer st = new StringTokenizer(files, "|");
1111 while (st.hasMoreElements())
1113 String file = st.nextToken();
1116 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1119 if (coloursFound.length() > 0)
1121 coloursFound.append("|");
1123 coloursFound.append(file);
1124 ColourSchemes.getInstance().registerColourScheme(ucs);
1126 } catch (Exception ex)
1128 System.out.println("Error loading User ColourFile\n" + ex);
1131 if (!files.equals(coloursFound.toString()))
1133 if (coloursFound.toString().length() > 1)
1135 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1136 coloursFound.toString());
1140 applicationProperties
1141 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1147 * Initial logging information helper for various versions output
1151 * @param defaultValue
1153 private static void appendIfNotNull(StringBuilder sb, String prefix,
1154 String value, String suffix, String defaultValue)
1156 if (value == null && defaultValue == null)
1162 sb.append(value == null ? defaultValue : value);
1169 * @return Jalview version, build details and JVM platform version for console
1171 public static String getVersionDetailsForConsole()
1173 StringBuilder sb = new StringBuilder();
1174 sb.append(ChannelProperties.getProperty("app_name"))
1175 .append(" Version: ");
1176 sb.append(Cache.getDefault("VERSION", "TEST"));
1178 sb.append(ChannelProperties.getProperty("app_name"))
1179 .append(" Installation: ");
1180 sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1182 sb.append("Build Date: ");
1183 sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1185 sb.append("Java version: ");
1186 sb.append(System.getProperty("java.version"));
1188 sb.append(System.getProperty("os.arch"));
1190 sb.append(System.getProperty("os.name"));
1192 sb.append(System.getProperty("os.version"));
1194 appendIfNotNull(sb, "Install4j version: ",
1195 System.getProperty("sys.install4jVersion"), "\n", null);
1196 appendIfNotNull(sb, "Install4j template version: ",
1197 System.getProperty("installer_template_version"), "\n", null);
1198 appendIfNotNull(sb, "Launcher version: ",
1199 System.getProperty("launcher_version"), "\n", null);
1200 LookAndFeel laf = UIManager.getLookAndFeel();
1201 String lafName = laf == null ? "Not obtained" : laf.getName();
1202 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1203 sb.append("LookAndFeel: ");
1206 sb.append(lafClass);
1208 if (Console.isDebugEnabled()
1209 || !"release".equals(ChannelProperties.getProperty("channel")))
1211 appendIfNotNull(sb, "Channel: ",
1212 ChannelProperties.getProperty("channel"), "\n", null);
1213 appendIfNotNull(sb, "Getdown appdir: ",
1214 System.getProperty("getdowninstanceappdir"), "\n", null);
1215 appendIfNotNull(sb, "Getdown appbase: ",
1216 System.getProperty("getdowninstanceappbase"), "\n", null);
1217 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1220 return sb.toString();
1225 * @return build details as reported in splashscreen
1227 public static String getBuildDetailsForSplash()
1229 // consider returning more human friendly info
1230 // eg 'built from Source' or update channel
1231 return Cache.getDefault("INSTALLATION", "unknown");
1234 public static String getStackTraceString(Throwable t)
1236 StringWriter sw = new StringWriter();
1237 PrintWriter pw = new PrintWriter(sw);
1238 t.printStackTrace(pw);
1239 return sw.toString();
1242 // proxy properties methods
1243 public static void clearProxyProperties()
1245 setProxyProperties(null, null, null, null, null, null, null, null,
1249 public static void resetProxyProperties()
1251 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1252 startupProxyProperties[2], startupProxyProperties[3],
1253 startupProxyProperties[4],
1254 startupProxyProperties[5] == null ? null
1255 : startupProxyProperties[5].toCharArray(),
1256 startupProxyProperties[6],
1257 startupProxyProperties[7] == null ? null
1258 : startupProxyProperties[7].toCharArray(),
1259 startupProxyProperties[8]);
1260 StringBuilder sb = new StringBuilder();
1261 sb.append("Setting proxy properties to: http.proxyHost=")
1262 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1263 .append(startupProxyProperties[1])
1264 .append(startupProxyProperties[4] != null
1265 && !startupProxyProperties[4].isEmpty()
1266 ? " [" + startupProxyProperties[4] + "]"
1268 .append(", https.proxyHost=").append(startupProxyProperties[2])
1269 .append(", https.proxyPort=").append(startupProxyProperties[3])
1270 .append(startupProxyProperties[6] != null
1271 && !startupProxyProperties[6].isEmpty()
1272 ? " [" + startupProxyProperties[6] + "]"
1275 Console.debug(sb.toString());
1278 public static void setProxyPropertiesFromPreferences()
1280 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1283 public static void setProxyPropertiesFromPreferences(
1284 String previousProxyType)
1286 String proxyType = Cache.getDefault("USE_PROXY",
1287 Cache.PROXYTYPE_SYSTEM);
1288 if (previousProxyType != null
1289 && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1291 && proxyType.equals(previousProxyType))
1298 case Cache.PROXYTYPE_NONE:
1299 if (!previousProxyType.equals(proxyType))
1301 Console.info("Setting no proxy settings");
1302 Cache.setProxyProperties(null, null, null, null, null, null, null,
1306 case Cache.PROXYTYPE_CUSTOM:
1307 // always re-set a custom proxy -- it might have changed, particularly
1309 Console.info("Setting custom proxy settings");
1310 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1311 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1312 Cache.getDefault("PROXY_PORT", null),
1313 Cache.getDefault("PROXY_SERVER_HTTPS", null),
1314 Cache.getDefault("PROXY_PORT_HTTPS", null),
1315 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1317 proxyAuthSet ? Cache.proxyAuthPassword : null,
1318 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1320 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1322 default: // system proxy settings by default
1323 Console.info("Setting system proxy settings");
1324 Cache.resetProxyProperties();
1328 public static void setProxyProperties(String httpHost, String httpPort,
1329 String httpsHost, String httpsPort, String httpUser,
1330 char[] httpPassword, String httpsUser, char[] httpsPassword,
1331 String nonProxyHosts)
1333 setOrClearSystemProperty("http.proxyHost", httpHost);
1334 setOrClearSystemProperty("http.proxyPort", httpPort);
1335 setOrClearSystemProperty("https.proxyHost", httpsHost);
1336 setOrClearSystemProperty("https.proxyPort", httpsPort);
1337 setOrClearSystemProperty("http.proxyUser", httpUser);
1338 setOrClearSystemProperty("https.proxyUser", httpsUser);
1339 // note: passwords for http.proxyPassword and https.proxyPassword are sent
1340 // via the Authenticator, properties do not need to be set
1342 // are we using a custom proxy (password prompt might be required)?
1343 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1344 .equals(PROXYTYPE_CUSTOM);
1347 * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1348 * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1349 * is not re-called).
1350 * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1352 * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1354 * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1359 sun.net.www.protocol.http.AuthCacheValue
1360 .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1361 } catch (Throwable t)
1363 Cache.error(t.getMessage());
1364 Cache.debug(getStackTraceString(t));
1368 if (httpUser != null || httpsUser != null)
1372 char[] displayHttpPw = new char[httpPassword == null ? 0
1373 : httpPassword.length];
1374 Arrays.fill(displayHttpPw, '*');
1376 "CACHE Proxy: setting new Authenticator with httpUser='"
1377 + httpUser + "' httpPassword='" + displayHttpPw
1379 if (!Platform.isJS())
1381 * java.net.Authenticator not implemented in SwingJS yet
1387 Authenticator.setDefault(new Authenticator()
1390 protected PasswordAuthentication getPasswordAuthentication()
1392 if (getRequestorType() == RequestorType.PROXY)
1394 String protocol = getRequestingProtocol();
1395 boolean needProxyPasswordSet = false;
1396 if (customProxySet &&
1397 // we have a username but no password for the scheme being
1399 (protocol.equalsIgnoreCase("http")
1400 && (httpUser != null && httpUser.length() > 0
1401 && (httpPassword == null
1402 || httpPassword.length == 0)))
1403 || (protocol.equalsIgnoreCase("https")
1404 && (httpsUser != null
1405 && httpsUser.length() > 0
1406 && (httpsPassword == null
1407 || httpsPassword.length == 0))))
1409 // open Preferences -> Connections
1410 String message = MessageManager
1411 .getString("label.proxy_password_required");
1412 Preferences.openPreferences(
1413 Preferences.TabRef.CONNECTIONS_TAB, message);
1414 Preferences.getInstance()
1415 .proxyAuthPasswordCheckHighlight(true, true);
1421 if (protocol.equalsIgnoreCase("http")
1422 && getRequestingHost()
1423 .equalsIgnoreCase(httpHost)
1424 && getRequestingPort() == Integer
1428 "AUTHENTICATOR returning PasswordAuthentication(\""
1429 + httpUser + "\", '"
1430 + new String(displayHttpPw) + "')");
1431 return new PasswordAuthentication(httpUser,
1434 if (protocol.equalsIgnoreCase("https")
1435 && getRequestingHost()
1436 .equalsIgnoreCase(httpsHost)
1437 && getRequestingPort() == Integer
1438 .valueOf(httpsPort))
1440 char[] displayHttpsPw = new char[httpPassword.length];
1441 Arrays.fill(displayHttpsPw, '*');
1443 "AUTHENTICATOR returning PasswordAuthentication(\""
1444 + httpsUser + "\", '" + displayHttpsPw
1446 return new PasswordAuthentication(httpsUser,
1449 } catch (NumberFormatException e)
1451 Console.error("Problem with proxy port values [http:"
1452 + httpPort + ", https:" + httpsPort + "]");
1455 "AUTHENTICATOR after trying to get PasswordAuthentication");
1458 // non proxy request
1459 Console.debug("AUTHENTICATOR returning null");
1463 } // end of j2sIgnore for java.net.Authenticator
1465 // required to re-enable basic authentication (should be okay for a
1468 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1469 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1470 } catch (SecurityException e)
1472 Console.error("Could not set default Authenticator");
1473 Console.debug(getStackTraceString(e));
1478 // reset the Authenticator to protect http.proxyUser and
1479 // http.proxyPassword Just In Case
1480 /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1481 * has working credentials. No workaround for Java 11.
1483 if (!Platform.isJS())
1485 * java.net.Authenticator not implemented in SwingJS yet
1492 "AUTHENTICATOR setting default Authenticator to null");
1493 Authenticator.setDefault(null);
1497 // nonProxyHosts not currently configurable in Preferences
1499 "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1500 + nonProxyHosts + "\"");
1501 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1504 public static void setOrClearSystemProperty(String key, char[] value)
1506 setOrClearSystemProperty(key,
1507 (value == null) ? null : new String(value));
1510 public static void setOrClearSystemProperty(String key, String value)
1518 System.clearProperty(key);
1522 System.setProperty(key, value);
1527 * Getdown appbase methods
1530 private static final String releaseAppbase;
1532 private static String getdownAppbase;
1534 private static String getdownDistDir;
1538 if (!Platform.isJS())
1540 Float specversion = Float
1541 .parseFloat(System.getProperty("java.specification.version"));
1542 releaseAppbase = (specversion < 9)
1543 ? "https://www.jalview.org/getdown/release/1.8"
1544 : "https://www.jalview.org/getdown/release/11";
1548 // this value currenly made up, can be changed to URL that will be
1549 // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1550 releaseAppbase = "https://www.jalview.org/jalview-js";
1551 getdownAppbase = releaseAppbase;
1552 getdownDistDir = "/swingjs/j2s";
1556 // look for properties (passed in by getdown) otherwise default to release
1557 private static void setGetdownAppbase()
1559 if (getdownAppbase != null)
1563 String appbase = System.getProperty("getdownappbase");
1564 String distDir = System.getProperty("getdowndistdir");
1565 if (appbase == null)
1567 appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1568 distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1570 if (appbase == null)
1572 appbase = releaseAppbase;
1573 distDir = "release";
1575 if (appbase.endsWith("/"))
1577 appbase = appbase.substring(0, appbase.length() - 1);
1579 if (distDir == null)
1581 distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1583 getdownAppbase = appbase;
1584 getdownDistDir = distDir;
1587 public static String getGetdownAppbase()
1589 setGetdownAppbase();
1590 return getdownAppbase;
1593 public static String getAppbaseBuildProperties()
1595 String appbase = getGetdownAppbase();
1596 return appbase + "/" + getdownDistDir + "/build_properties";