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.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collections;
40 import java.util.Date;
41 import java.util.Enumeration;
42 import java.util.List;
43 import java.util.Locale;
44 import java.util.Properties;
45 import java.util.StringTokenizer;
46 import java.util.TreeSet;
48 import javax.swing.LookAndFeel;
49 import javax.swing.UIManager;
51 import jalview.analytics.Plausible;
52 import jalview.datamodel.PDBEntry;
53 import jalview.gui.Preferences;
54 import jalview.gui.UserDefinedColours;
55 import jalview.log.JLoggerLog4j;
56 import jalview.schemes.ColourSchemeLoader;
57 import jalview.schemes.ColourSchemes;
58 import jalview.schemes.UserColourScheme;
59 import jalview.structure.StructureImportSettings;
60 import jalview.urls.IdOrgSettings;
61 import jalview.util.ChannelProperties;
62 import jalview.util.ColorUtils;
63 import jalview.util.MessageManager;
64 import jalview.util.Platform;
65 import jalview.ws.sifts.SiftsSettings;
68 * Stores and retrieves Jalview Application Properties Lists and fields within
69 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
70 * are alternative values for a tag. <br>
72 * Current properties include:
75 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
76 * logging level for axis (used for web services) <br>
78 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
79 * the logging level for castor (used for serialization) <br>
81 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
83 * <li>SCREEN_WIDTH</li>
84 * <li>SCREEN_HEIGHT</li>
85 * <li>SCREEN_Y=285</li>
86 * <li>SCREEN_X=371</li>
87 * <li>SHOW_FULLSCREEN boolean</li>
88 * <li>FONT_NAME java font name for alignment text display</li>
89 * <li>FONT_SIZE size of displayed alignment text</li>
90 * <li>FONT_STYLE style of font displayed (sequence labels are always
92 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
93 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
94 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
95 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
96 * <li>SHOW_IDENTITY show percentage identity annotation</li>
97 * <li>SHOW_QUALITY show alignment quality annotation</li>
98 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
99 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
100 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
101 * LABEL_AND_SEQUENCE</li>
102 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
103 * sequence annotations</li>
104 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
105 * annotation row</li>
106 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
107 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
108 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
109 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
110 * <li>VERSION the version of the jalview build</li>
111 * <li>BUILD_DATE date of this build</li>
112 * <li>LATEST_VERSION the latest jalview version advertised on the
113 * www.jalview.org</li>
114 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
116 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
117 * suffix to file</li>
118 * <li>RECENT_URL list of recently retrieved URLs</li>
119 * <li>RECENT_FILE list of recently opened files</li>
120 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
121 * <li>PROXY_SERVER the proxy</li>
122 * <li>PROXY_PORT</li>
123 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
125 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
127 * <li>USAGESTATS (false - user prompted) Enable analytics tracker for
128 * collecting usage statistics</li>
129 * <li>SHOW_OVERVIEW boolean for overview window display</li>
130 * <li>ANTI_ALIAS boolean for smooth fonts</li>
131 * <li>RIGHT_ALIGN_IDS boolean</li>
132 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
133 * <li>PAD_GAPS boolean</li>
134 * <li>ID_ITALICS boolean</li>
135 * <li>SHOW_JV_SUFFIX</li>
136 * <li>WRAP_ALIGNMENT</li>
137 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
139 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
140 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
142 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
144 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
145 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
146 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
147 * jalview.utils.GroupURLLink for more info</li>
148 * <li>DEFAULT_BROWSER for unix</li>
149 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
151 * <li>VERSION_CHECK (true) check for the latest release version from
152 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
153 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
155 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
157 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
158 * displayed as '.'</li>
159 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
160 * order of a newly displayed tree</li>
161 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
162 * sequence ID strings before attempting retrieval from any datasource</li>
163 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
165 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
166 * in the alignment.</li>
167 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
169 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
171 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
172 * logo normalised to row height rather than histogram height.</li>
173 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
174 * respond to selections made in other alignments containing the same sequences.
176 * <li>SHOW_JWS2_SERVICES (true) when set to false, jalview will not
177 * auto-discover JABAWS services</li>
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 (https://www.jalview.org) a property enabling all HTTP
186 * requests to be redirected to a mirror of https://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
205 * <li>NONEWS - when set disables Jalview News from automatically appearing</li>
206 * <li>NOHTMLTEMPLATES - when set, the
207 * https://github.com/jalview/exporter-templates/tree/master/biojs repository is
208 * not downloaded automatically</li>
209 * <li>NOIDENTIFIERSSERVICE - when set, jalview won't automatically download
210 * available URL linkouts via www.jalview.org/services/identifiers</li>
213 * Deprecated settings:
216 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
217 * startup (JWS1 services only)</li>
218 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
219 * (JWS1 services only)</li>
220 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
221 * services in the desktop GUI</li>
222 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
223 * panel in web service preferences</li>
227 * @version $Revision$
232 * property giving log4j level for CASTOR loggers
234 public static final String CASTORLOGLEVEL = "logs.Castor.level";
237 * property giving log4j level for AXIS loggers
239 public static final String AXISLOGLEVEL = "logs.Axis.level";
242 * property giving log4j level for Jalview Log
244 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
249 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
250 .getProperty("user.home") + File.separatorChar
251 + ".sifts_downloads" + File.separatorChar;
253 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
255 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
258 * Identifiers.org download settings
260 private static final String ID_ORG_FILE = System.getProperty("user.home")
261 + File.separatorChar + ".identifiers.org.ids.json";
264 * Allowed values are PDB or mmCIF
266 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
269 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
273 * a date formatter using a fixed (rather than the user's) locale;
274 * this ensures that date properties can be written and re-read successfully
275 * even if the user changes their locale setting
277 private static final DateFormat date_format = SimpleDateFormat
278 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
279 SimpleDateFormat.MEDIUM, Locale.UK);
282 * Initialises the Jalview Application Log
285 public final static String JALVIEW_LOGGER_NAME = "JalviewLogger";
287 // save the proxy properties set at startup
288 public final static String[] startupProxyProperties = {
289 System.getProperty("http.proxyHost"),
290 System.getProperty("http.proxyPort"),
291 System.getProperty("https.proxyHost"),
292 System.getProperty("https.proxyPort"),
293 System.getProperty("http.proxyUser"),
294 System.getProperty("http.proxyPassword"),
295 System.getProperty("https.proxyUser"),
296 System.getProperty("https.proxyPassword"),
297 System.getProperty("http.nonProxyHosts") };
299 public final static String PROXYTYPE_NONE = "none";
301 // "false" and "true" for backward compatibility
302 public final static String PROXYTYPE_SYSTEM = "false";
304 public final static String PROXYTYPE_CUSTOM = "true";
306 // in-memory only storage of proxy password, safer to use char array
307 public static char[] proxyAuthPassword = null;
309 /** Jalview Properties */
310 public static Properties applicationProperties = new Properties()
312 // override results in properties output in alphabetical order
314 public synchronized Enumeration<Object> keys()
316 return Collections.enumeration(new TreeSet<>(super.keySet()));
320 /* build Properties (not all saved to .jalview_properties) */
321 public static Properties buildProperties = new Properties();
323 /** Default file is ~/.jalview_properties */
324 static String propertiesFile;
326 private static boolean propsAreReadOnly = Platform.isJS();
328 private final static String JS_PROPERTY_PREFIX = "jalview_";
331 * Loads properties from the given properties file. Any existing properties
334 public static void loadProperties(String propsFile)
336 propertiesFile = propsFile;
337 String releasePropertiesFile = null;
338 boolean defaultProperties = false;
339 if (propsFile == null && !propsAreReadOnly)
341 String channelPrefsFilename = ChannelProperties
342 .getProperty("preferences.filename");
343 String releasePrefsFilename = ".jalview_properties";
344 propertiesFile = System.getProperty("user.home") + File.separatorChar
345 + channelPrefsFilename;
346 releasePropertiesFile = System.getProperty("user.home")
347 + File.separatorChar + releasePrefsFilename;
348 defaultProperties = true;
352 // don't corrupt the file we've been given.
353 propsAreReadOnly = true;
356 if (propertiesFile == null)
358 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
359 applicationProperties);
368 // props file provided as URL
369 fis = new URL(propertiesFile).openStream();
371 "Loading jalview properties from : " + propertiesFile);
373 "Disabling Jalview writing to user's local properties file.");
374 propsAreReadOnly = true;
375 } catch (Exception ex)
381 String readPropertiesFile = propertiesFile;
382 // if we're using the usual properties file and the channel properties
383 // file doesn't exist, read .jalview_properties
384 // (but we'll still save to the channel properties file).
385 if (defaultProperties && (!new File(propertiesFile).exists())
386 && (new File(releasePropertiesFile).exists()))
388 readPropertiesFile = releasePropertiesFile;
390 fis = new FileInputStream(readPropertiesFile);
392 applicationProperties.clear();
393 applicationProperties.load(fis);
395 // remove any old build properties
397 deleteBuildProperties();
399 } catch (Exception ex)
401 System.out.println("Error reading properties file: " + ex);
405 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
406 if (getDefault("USE_PROXY", false))
408 String proxyServer = getDefault("PROXY_SERVER", ""),
409 proxyPort = getDefault("PROXY_PORT", "8080");
413 // PROXY TYPE settings (now three options "none", "false", "true", but using
414 // backward compatible strings)
415 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
416 // default to upgrading old settings
420 clearProxyProperties();
422 case PROXYTYPE_SYSTEM: // use system settings
423 resetProxyProperties();
425 case PROXYTYPE_CUSTOM: // use specified proxy settings
426 String httpHost = getDefault("PROXY_SERVER", "");
427 String httpPort = getDefault("PROXY_PORT", "8080");
428 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
429 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
430 String httpUser = getDefault("PROXY_AUTH_USER", null);
431 // https.proxyUser and https.proxyPassword are not able to be
432 // independently set in Preferences yet (or http.nonProxyHosts)
433 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
434 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
435 proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
438 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
440 Console.warn(message);
443 // LOAD THE AUTHORS FROM THE authors.props file
444 String authorDetails = resolveResourceURLFor("/authors.props");
448 if (authorDetails != null)
450 URL localJarFileURL = new URL(authorDetails);
451 InputStream in = localJarFileURL.openStream();
452 applicationProperties.load(in);
455 } catch (Exception ex)
457 System.out.println("Error reading author details: " + ex);
458 authorDetails = null;
460 if (authorDetails == null)
462 applicationProperties.remove("AUTHORS");
463 applicationProperties.remove("AUTHORFNAMES");
464 applicationProperties.remove("YEAR");
467 loadBuildProperties(false);
470 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
472 SiftsSettings.setSiftDownloadDirectory(Cache
473 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
475 SiftsSettings.setFailSafePIDThreshold(
476 Cache.getDefault("sifts_fail_safe_pid_threshold",
477 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
479 SiftsSettings.setCacheThresholdInDays(
480 Cache.getDefault("sifts_cache_threshold_in_days",
481 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
483 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
484 "https://www.jalview.org/services/identifiers"));
485 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
487 StructureImportSettings.setDefaultStructureFileFormat(
488 Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
489 StructureImportSettings
490 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
491 // StructureImportSettings
492 // .setDefaultPDBFileParser(Cache.getDefault(
493 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
495 String jnlpVersion = System.getProperty("jalview.version");
497 // jnlpVersion will be null if a latest version check for the channel needs
499 // Dont do this check if running in headless mode
501 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
502 && (System.getProperty("java.awt.headless") == null || System
503 .getProperty("java.awt.headless").equals("false")))
506 class VersionChecker extends Thread
512 String remoteBuildPropertiesUrl = Cache
513 .getAppbaseBuildProperties();
515 String orgtimeout = System
516 .getProperty("sun.net.client.defaultConnectTimeout");
517 if (orgtimeout == null)
520 System.out.println("# INFO: Setting default net timeout to "
521 + orgtimeout + " seconds.");
523 String remoteVersion = null;
524 if (remoteBuildPropertiesUrl.startsWith("http"))
528 System.setProperty("sun.net.client.defaultConnectTimeout",
531 URL url = new URL(remoteBuildPropertiesUrl);
533 BufferedReader in = new BufferedReader(
534 new InputStreamReader(url.openStream()));
536 Properties remoteBuildProperties = new Properties();
537 remoteBuildProperties.load(in);
538 remoteVersion = remoteBuildProperties.getProperty("VERSION");
539 } catch (Exception ex)
542 "Non-fatal exception when checking version at "
543 + remoteBuildPropertiesUrl + ":");
544 System.out.println(ex);
545 remoteVersion = getProperty("VERSION");
548 System.setProperty("sun.net.client.defaultConnectTimeout",
551 setProperty("LATEST_VERSION", remoteVersion);
555 VersionChecker vc = new VersionChecker();
560 if (jnlpVersion != null)
562 setProperty("LATEST_VERSION", jnlpVersion);
566 applicationProperties.remove("LATEST_VERSION");
570 // LOAD USERDEFINED COLOURS
571 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
572 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
577 * construct a resource URL for the given absolute resource pathname
579 * @param resourcePath
582 private static String resolveResourceURLFor(String resourcePath)
585 if (Platform.isJS() || !Cache.class.getProtectionDomain()
586 .getCodeSource().getLocation().toString().endsWith(".jar"))
590 url = Cache.class.getResource(resourcePath).toString();
591 } catch (Exception ex)
593 System.err.println("Failed to resolve resource " + resourcePath
594 + ": " + ex.getMessage());
599 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
600 .getLocation().toString().concat("!" + resourcePath));
605 public static void loadBuildProperties(boolean reportVersion)
607 String codeInstallation = getProperty("INSTALLATION");
608 boolean printVersion = codeInstallation == null;
611 * read build properties - from the Jalview jar for a Java distribution,
612 * or from codebase file in test or JalviewJS context
616 String buildDetails = resolveResourceURLFor("/.build_properties");
617 URL localJarFileURL = new URL(buildDetails);
618 InputStream in = localJarFileURL.openStream();
619 buildProperties.load(in);
621 if (buildProperties.getProperty("BUILD_DATE", null) != null)
623 applicationProperties.put("BUILD_DATE",
624 buildProperties.getProperty("BUILD_DATE"));
626 if (buildProperties.getProperty("INSTALLATION", null) != null)
628 applicationProperties.put("INSTALLATION",
629 buildProperties.getProperty("INSTALLATION"));
631 if (buildProperties.getProperty("VERSION", null) != null)
633 applicationProperties.put("VERSION",
634 buildProperties.getProperty("VERSION"));
636 if (buildProperties.getProperty("JAVA_COMPILE_VERSION", null) != null)
638 applicationProperties.put("JAVA_COMPILE_VERSION",
639 buildProperties.getProperty("JAVA_COMPILE_VERSION"));
641 } catch (Exception ex)
643 System.out.println("Error reading build details: " + ex);
644 applicationProperties.remove("VERSION");
646 String codeVersion = getProperty("VERSION");
647 codeInstallation = getProperty("INSTALLATION");
649 if (codeVersion == null)
651 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
652 codeVersion = "Test";
653 codeInstallation = "";
657 codeInstallation = " (" + codeInstallation + ")";
659 setProperty("VERSION", codeVersion);
660 new BuildDetails(codeVersion, null, codeInstallation);
661 if (printVersion && reportVersion)
663 System.out.println(ChannelProperties.getProperty("app_name")
664 + " Version: " + codeVersion + codeInstallation);
668 private static void deleteBuildProperties()
670 applicationProperties.remove("LATEST_VERSION");
671 applicationProperties.remove("VERSION");
672 applicationProperties.remove("AUTHORS");
673 applicationProperties.remove("AUTHORFNAMES");
674 applicationProperties.remove("YEAR");
675 applicationProperties.remove("BUILD_DATE");
676 applicationProperties.remove("INSTALLATION");
680 * Gets Jalview application property of given key. Returns null if key not
686 * @return Property value
688 public static String getProperty(String key)
690 String prop = applicationProperties.getProperty(key);
691 if (prop == null && Platform.isJS())
693 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
694 + "_" + JS_PROPERTY_PREFIX + key);
700 * These methods are used when checking if the saved preference is different
701 * to the default setting
704 public static boolean getDefault(String property, boolean def)
706 String string = getProperty(property);
709 def = Boolean.valueOf(string).booleanValue();
715 public static int getDefault(String property, int def)
717 String string = getProperty(property);
722 def = Integer.parseInt(string);
723 } catch (NumberFormatException e)
725 System.out.println("Error parsing int property '" + property
726 + "' with value '" + string + "'");
734 * Answers the value of the given property, or the supplied default value if
735 * the property is not set
737 public static String getDefault(String property, String def)
739 String value = getProperty(property);
740 return value == null ? def : value;
744 * Stores property in the file "HOME_DIR/.jalview_properties"
749 * String value of property
751 * @return previous value of property (or null)
753 public static Object setProperty(String key, String obj)
755 Object oldValue = null;
758 oldValue = applicationProperties.setProperty(key, obj);
759 if (propertiesFile != null && !propsAreReadOnly)
761 FileOutputStream out = new FileOutputStream(propertiesFile);
762 applicationProperties.store(out, "---JalviewX Properties File---");
765 } catch (Exception ex)
768 "Error setting property: " + key + " " + obj + "\n" + ex);
774 * remove the specified property from the jalview properties file
778 public static void removeProperty(String string)
780 applicationProperties.remove(string);
785 * save the properties to the jalview properties path
787 public static void saveProperties()
789 if (!propsAreReadOnly)
793 FileOutputStream out = new FileOutputStream(propertiesFile);
794 applicationProperties.store(out, "---JalviewX Properties File---");
796 } catch (Exception ex)
798 System.out.println("Error saving properties: " + ex);
804 * internal vamsas class discovery state
806 private static int vamsasJarsArePresent = -1;
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 == -1)
819 if (jalview.jbgui.GDesktop.class.getClassLoader()
820 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
823 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
824 vamsasJarsArePresent = 1;
825 JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
826 Console.getCachedLogLevel("logs.Vamsas.Level"));
827 JLoggerLog4j.addAppender(lvclient, Console.log,
828 JALVIEW_LOGGER_NAME);
829 // Tell the user that debug is enabled
830 lvclient.debug(ChannelProperties.getProperty("app_name")
831 + " Vamsas Client Debugging Output Follows.");
833 } catch (Exception e)
835 vamsasJarsArePresent = 0;
836 Console.debug("Vamsas Classes are not present");
839 return (vamsasJarsArePresent > 0);
843 * internal vamsas class discovery state
845 private static int groovyJarsArePresent = -1;
848 * Searches for vamsas client classes on class path.
850 * @return true if vamsas client is present on classpath
852 public static boolean groovyJarsPresent()
854 if (groovyJarsArePresent == -1)
858 if (Cache.class.getClassLoader()
859 .loadClass("groovy.lang.GroovyObject") != null)
862 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
863 groovyJarsArePresent = 1;
864 JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
865 Console.getCachedLogLevel("logs.Groovy.Level"));
866 JLoggerLog4j.addAppender(lgclient, Console.log,
867 JALVIEW_LOGGER_NAME);
868 // Tell the user that debug is enabled
869 lgclient.debug(ChannelProperties.getProperty("app_name")
870 + " Groovy Client Debugging Output Follows.");
874 groovyJarsArePresent = 0;
875 Console.debug("Groovy Classes are not present", e);
876 } catch (Exception e)
878 groovyJarsArePresent = 0;
879 Console.debug("Groovy Classes are not present");
882 return (groovyJarsArePresent > 0);
886 * Initialise the tracker if it is not done already.
888 public static void initAnalytics()
890 Plausible.setEnabled(true);
892 String appName = ChannelProperties.getProperty("app_name") + " Desktop";
893 String version = Cache.getProperty("VERSION") + "_"
894 + Cache.getDefault("BUILD_DATE", "unknown");
896 /* we don't want to encode ':' as "%3A" for backward compatibility with the UA setup
899 path = "/" + String.join("/", URLEncoder.encode(appName, "UTF-8"),
900 URLEncoder.encode(version, "UTF-8"),
901 URLEncoder.encode(APPLICATION_STARTED, "UTF-8"));
902 } catch (UnsupportedEncodingException e)
905 List<String> pathParts = new ArrayList<>();
906 pathParts.add(appName);
907 pathParts.add(version);
908 pathParts.add(APPLICATION_STARTED);
909 path = ("/" + String.join("/", pathParts)).replace(' ', '+');
913 Plausible plausible = Plausible.getInstance();
915 // This will send a new "application_launch" event with parameters
916 // including the old-style "path", the channel name and version
917 plausible.sendEvent("application_launch", path, true);
920 private static final String APPLICATION_STARTED = "Application Started";
923 * get the user's default colour if available
929 public static Color getDefaultColour(String property, Color defcolour)
931 String colprop = getProperty(property);
936 Color col = ColorUtils.parseColourString(colprop);
939 Console.warn("Couldn't parse '" + colprop + "' as a colour for "
942 return (col == null) ? defcolour : col;
946 * store a colour as a Jalview user default property
951 public static void setColourProperty(String property, Color colour)
953 setProperty(property, jalview.util.Format.getHexString(colour));
957 * Stores a formatted date in a jalview property, using a fixed locale.
959 * @param propertyName
961 * @return the formatted date string
963 public static String setDateProperty(String propertyName, Date date)
965 String formatted = date_format.format(date);
966 setProperty(propertyName, formatted);
971 * Reads a date stored in a Jalview property, parses it (using a fixed locale
972 * format) and returns as a Date, or null if parsing fails
974 * @param propertyName
978 public static Date getDateProperty(String propertyName)
980 String val = getProperty(propertyName);
985 return date_format.parse(val);
986 } catch (Exception ex)
988 System.err.println("Invalid or corrupt date in property '"
989 + propertyName + "' : value was '" + val + "'");
996 * get and parse a property as an integer. send any parsing problems to
1000 * @return null or Integer
1002 public static Integer getIntegerProperty(String property)
1004 String val = getProperty(property);
1005 if (val != null && (val = val.trim()).length() > 0)
1009 return Integer.valueOf(val);
1010 } catch (NumberFormatException x)
1012 System.err.println("Invalid integer in property '" + property
1013 + "' (value was '" + val + "')");
1020 * Set the specified value, or remove it if null or empty. Does not save the
1026 public static void setOrRemove(String propName, String value)
1028 if (propName == null)
1032 if (value == null || value.trim().length() < 1)
1034 Cache.applicationProperties.remove(propName);
1038 Cache.applicationProperties.setProperty(propName, value);
1043 * Loads in user colour schemes from files.
1046 * a '|'-delimited list of file paths
1048 public static void initUserColourSchemes(String files)
1050 if (files == null || files.length() == 0)
1055 // In case colours can't be loaded, we'll remove them
1056 // from the default list here.
1057 StringBuffer coloursFound = new StringBuffer();
1058 StringTokenizer st = new StringTokenizer(files, "|");
1059 while (st.hasMoreElements())
1061 String file = st.nextToken();
1064 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1067 if (coloursFound.length() > 0)
1069 coloursFound.append("|");
1071 coloursFound.append(file);
1072 ColourSchemes.getInstance().registerColourScheme(ucs);
1074 } catch (Exception ex)
1076 System.out.println("Error loading User ColourFile\n" + ex);
1079 if (!files.equals(coloursFound.toString()))
1081 if (coloursFound.toString().length() > 1)
1083 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1084 coloursFound.toString());
1088 applicationProperties
1089 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1095 * Initial logging information helper for various versions output
1099 * @param defaultValue
1101 private static void appendIfNotNull(StringBuilder sb, String prefix,
1102 String value, String suffix, String defaultValue)
1104 if (value == null && defaultValue == null)
1110 sb.append(value == null ? defaultValue : value);
1117 * @return Jalview version, build details and JVM platform version for console
1119 public static String getVersionDetailsForConsole()
1121 StringBuilder sb = new StringBuilder();
1122 sb.append(ChannelProperties.getProperty("app_name"))
1123 .append(" Version: ");
1124 sb.append(Cache.getDefault("VERSION", "TEST"));
1126 sb.append(ChannelProperties.getProperty("app_name"))
1127 .append(" Installation: ");
1128 sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1130 sb.append("Build Date: ");
1131 sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1133 sb.append("Java version: ");
1134 sb.append(System.getProperty("java.version"));
1136 sb.append(System.getProperty("os.arch"));
1138 sb.append(System.getProperty("os.name"));
1140 sb.append(System.getProperty("os.version"));
1142 appendIfNotNull(sb, "Install4j version: ",
1143 System.getProperty("sys.install4jVersion"), "\n", null);
1144 appendIfNotNull(sb, "Install4j template version: ",
1145 System.getProperty("installer_template_version"), "\n", null);
1146 appendIfNotNull(sb, "Launcher version: ",
1147 System.getProperty("launcher_version"), "\n", null);
1148 LookAndFeel laf = UIManager.getLookAndFeel();
1149 String lafName = laf == null ? "Not obtained" : laf.getName();
1150 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1151 sb.append("LookAndFeel: ");
1154 sb.append(lafClass);
1156 if (Console.isDebugEnabled()
1157 || !"release".equals(ChannelProperties.getProperty("channel")))
1159 appendIfNotNull(sb, "Channel: ",
1160 ChannelProperties.getProperty("channel"), "\n", null);
1161 appendIfNotNull(sb, "Getdown appdir: ",
1162 System.getProperty("getdowninstanceappdir"), "\n", null);
1163 appendIfNotNull(sb, "Getdown appbase: ",
1164 System.getProperty("getdowninstanceappbase"), "\n", null);
1165 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1168 return sb.toString();
1173 * @return build details as reported in splashscreen
1175 public static String getBuildDetailsForSplash()
1177 // consider returning more human friendly info
1178 // eg 'built from Source' or update channel
1179 return Cache.getDefault("INSTALLATION", "unknown");
1182 public static String getStackTraceString(Throwable t)
1184 StringWriter sw = new StringWriter();
1185 PrintWriter pw = new PrintWriter(sw);
1186 t.printStackTrace(pw);
1187 return sw.toString();
1190 // proxy properties methods
1191 public static void clearProxyProperties()
1193 setProxyProperties(null, null, null, null, null, null, null, null,
1197 public static void resetProxyProperties()
1199 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1200 startupProxyProperties[2], startupProxyProperties[3],
1201 startupProxyProperties[4],
1202 startupProxyProperties[5] == null ? null
1203 : startupProxyProperties[5].toCharArray(),
1204 startupProxyProperties[6],
1205 startupProxyProperties[7] == null ? null
1206 : startupProxyProperties[7].toCharArray(),
1207 startupProxyProperties[8]);
1208 StringBuilder sb = new StringBuilder();
1209 sb.append("Setting proxy properties to: http.proxyHost=")
1210 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1211 .append(startupProxyProperties[1])
1212 .append(startupProxyProperties[4] != null
1213 && !startupProxyProperties[4].isEmpty()
1214 ? " [" + startupProxyProperties[4] + "]"
1216 .append(", https.proxyHost=").append(startupProxyProperties[2])
1217 .append(", https.proxyPort=").append(startupProxyProperties[3])
1218 .append(startupProxyProperties[6] != null
1219 && !startupProxyProperties[6].isEmpty()
1220 ? " [" + startupProxyProperties[6] + "]"
1223 Console.debug(sb.toString());
1226 public static void setProxyPropertiesFromPreferences()
1228 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1231 public static void setProxyPropertiesFromPreferences(
1232 String previousProxyType)
1234 String proxyType = Cache.getDefault("USE_PROXY",
1235 Cache.PROXYTYPE_SYSTEM);
1236 if (previousProxyType != null
1237 && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1239 && proxyType.equals(previousProxyType))
1246 case Cache.PROXYTYPE_NONE:
1247 if (!previousProxyType.equals(proxyType))
1249 Console.info("Setting no proxy settings");
1250 Cache.setProxyProperties(null, null, null, null, null, null, null,
1254 case Cache.PROXYTYPE_CUSTOM:
1255 // always re-set a custom proxy -- it might have changed, particularly
1257 Console.info("Setting custom proxy settings");
1258 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1259 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1260 Cache.getDefault("PROXY_PORT", null),
1261 Cache.getDefault("PROXY_SERVER_HTTPS", null),
1262 Cache.getDefault("PROXY_PORT_HTTPS", null),
1263 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1265 proxyAuthSet ? Cache.proxyAuthPassword : null,
1266 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1268 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1270 default: // system proxy settings by default
1271 Console.info("Setting system proxy settings");
1272 Cache.resetProxyProperties();
1276 public static void setProxyProperties(String httpHost, String httpPort,
1277 String httpsHost, String httpsPort, String httpUser,
1278 char[] httpPassword, String httpsUser, char[] httpsPassword,
1279 String nonProxyHosts)
1281 setOrClearSystemProperty("http.proxyHost", httpHost);
1282 setOrClearSystemProperty("http.proxyPort", httpPort);
1283 setOrClearSystemProperty("https.proxyHost", httpsHost);
1284 setOrClearSystemProperty("https.proxyPort", httpsPort);
1285 setOrClearSystemProperty("http.proxyUser", httpUser);
1286 setOrClearSystemProperty("https.proxyUser", httpsUser);
1287 // note: passwords for http.proxyPassword and https.proxyPassword are sent
1288 // via the Authenticator, properties do not need to be set
1290 // are we using a custom proxy (password prompt might be required)?
1291 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1292 .equals(PROXYTYPE_CUSTOM);
1295 * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1296 * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1297 * is not re-called).
1298 * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1300 * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1302 * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1307 sun.net.www.protocol.http.AuthCacheValue
1308 .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1309 } catch (Throwable t)
1311 Cache.error(t.getMessage());
1312 Cache.debug(getStackTraceString(t));
1316 if (httpUser != null || httpsUser != null)
1320 char[] displayHttpPw = new char[httpPassword == null ? 0
1321 : httpPassword.length];
1322 Arrays.fill(displayHttpPw, '*');
1324 "CACHE Proxy: setting new Authenticator with httpUser='"
1325 + httpUser + "' httpPassword='" + displayHttpPw
1327 if (!Platform.isJS())
1329 * java.net.Authenticator not implemented in SwingJS yet
1335 Authenticator.setDefault(new Authenticator()
1338 protected PasswordAuthentication getPasswordAuthentication()
1340 if (getRequestorType() == RequestorType.PROXY)
1342 String protocol = getRequestingProtocol();
1343 boolean needProxyPasswordSet = false;
1344 if (customProxySet &&
1345 // we have a username but no password for the scheme being
1347 (protocol.equalsIgnoreCase("http")
1348 && (httpUser != null
1349 && httpUser.length() > 0
1350 && (httpPassword == null
1351 || httpPassword.length == 0)))
1352 || (protocol.equalsIgnoreCase("https")
1353 && (httpsUser != null
1354 && httpsUser.length() > 0
1355 && (httpsPassword == null
1356 || httpsPassword.length == 0))))
1358 // open Preferences -> Connections
1359 String message = MessageManager
1360 .getString("label.proxy_password_required");
1361 Preferences.openPreferences(
1362 Preferences.TabRef.CONNECTIONS_TAB, message);
1363 Preferences.getInstance()
1364 .proxyAuthPasswordCheckHighlight(true, true);
1370 if (protocol.equalsIgnoreCase("http")
1371 && getRequestingHost()
1372 .equalsIgnoreCase(httpHost)
1373 && getRequestingPort() == Integer
1377 "AUTHENTICATOR returning PasswordAuthentication(\""
1378 + httpUser + "\", '"
1379 + new String(displayHttpPw) + "')");
1380 return new PasswordAuthentication(httpUser,
1383 if (protocol.equalsIgnoreCase("https")
1384 && getRequestingHost()
1385 .equalsIgnoreCase(httpsHost)
1386 && getRequestingPort() == Integer
1387 .valueOf(httpsPort))
1389 char[] displayHttpsPw = new char[httpPassword.length];
1390 Arrays.fill(displayHttpsPw, '*');
1392 "AUTHENTICATOR returning PasswordAuthentication(\""
1393 + httpsUser + "\", '" + displayHttpsPw
1395 return new PasswordAuthentication(httpsUser,
1398 } catch (NumberFormatException e)
1400 Console.error("Problem with proxy port values [http:"
1401 + httpPort + ", https:" + httpsPort + "]");
1404 "AUTHENTICATOR after trying to get PasswordAuthentication");
1407 // non proxy request
1408 Console.debug("AUTHENTICATOR returning null");
1412 } // end of j2sIgnore for java.net.Authenticator
1414 // required to re-enable basic authentication (should be okay for a
1417 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1418 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1419 } catch (SecurityException e)
1421 Console.error("Could not set default Authenticator");
1422 Console.debug(getStackTraceString(e));
1427 // reset the Authenticator to protect http.proxyUser and
1428 // http.proxyPassword Just In Case
1429 /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1430 * has working credentials. No workaround for Java 11.
1432 if (!Platform.isJS())
1434 * java.net.Authenticator not implemented in SwingJS yet
1441 "AUTHENTICATOR setting default Authenticator to null");
1442 Authenticator.setDefault(null);
1446 // nonProxyHosts not currently configurable in Preferences
1448 "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1449 + nonProxyHosts + "\"");
1450 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1453 public static void setOrClearSystemProperty(String key, char[] value)
1455 setOrClearSystemProperty(key,
1456 (value == null) ? null : new String(value));
1459 public static void setOrClearSystemProperty(String key, String value)
1467 System.clearProperty(key);
1471 System.setProperty(key, value);
1476 * Getdown appbase methods
1479 private static final String releaseAppbase;
1481 private static String getdownAppbase;
1483 private static String getdownDistDir;
1487 if (!Platform.isJS())
1489 Float specversion = Float
1490 .parseFloat(System.getProperty("java.specification.version"));
1491 releaseAppbase = (specversion < 9)
1492 ? "https://www.jalview.org/getdown/release/1.8"
1493 : "https://www.jalview.org/getdown/release/11";
1497 // this value currenly made up, can be changed to URL that will be
1498 // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1499 releaseAppbase = "https://www.jalview.org/jalview-js";
1500 getdownAppbase = releaseAppbase;
1501 getdownDistDir = "/swingjs/j2s";
1505 // look for properties (passed in by getdown) otherwise default to release
1506 private static void setGetdownAppbase()
1508 if (getdownAppbase != null)
1512 String appbase = System.getProperty("getdownappbase");
1513 String distDir = System.getProperty("getdowndistdir");
1514 if (appbase == null)
1516 appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1517 distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1519 if (appbase == null)
1521 appbase = releaseAppbase;
1522 distDir = "release";
1524 if (appbase.endsWith("/"))
1526 appbase = appbase.substring(0, appbase.length() - 1);
1528 if (distDir == null)
1530 distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1532 getdownAppbase = appbase;
1533 getdownDistDir = distDir;
1536 public static String getGetdownAppbase()
1538 setGetdownAppbase();
1539 return getdownAppbase;
1542 public static String getAppbaseBuildProperties()
1544 String appbase = getGetdownAppbase();
1545 return appbase + "/" + getdownDistDir + "/build_properties";