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 public static boolean isPropsAreReadOnly()
327 return propsAreReadOnly;
330 public static void setPropsAreReadOnly(boolean propsAreReadOnly)
332 Cache.propsAreReadOnly = propsAreReadOnly;
335 private final static String JS_PROPERTY_PREFIX = "jalview_";
338 * Loads properties from the given properties file. Any existing properties
341 public static void loadProperties(String propsFile)
343 propertiesFile = propsFile;
344 String releasePropertiesFile = null;
345 boolean defaultProperties = false;
346 if (propsFile == null && !propsAreReadOnly)
348 String channelPrefsFilename = ChannelProperties
349 .getProperty("preferences.filename");
350 String releasePrefsFilename = ".jalview_properties";
351 propertiesFile = System.getProperty("user.home") + File.separatorChar
352 + channelPrefsFilename;
353 releasePropertiesFile = System.getProperty("user.home")
354 + File.separatorChar + releasePrefsFilename;
355 defaultProperties = true;
359 // don't corrupt the file we've been given.
360 propsAreReadOnly = true;
363 if (propertiesFile == null)
365 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
366 applicationProperties);
375 // props file provided as URL
376 fis = new URL(propertiesFile).openStream();
378 "Loading jalview properties from : " + propertiesFile);
380 "Disabling Jalview writing to user's local properties file.");
381 propsAreReadOnly = true;
382 } catch (Exception ex)
388 String readPropertiesFile = propertiesFile;
389 // if we're using the usual properties file and the channel properties
390 // file doesn't exist, read .jalview_properties
391 // (but we'll still save to the channel properties file).
392 if (defaultProperties && (!new File(propertiesFile).exists())
393 && (new File(releasePropertiesFile).exists()))
395 readPropertiesFile = releasePropertiesFile;
397 fis = new FileInputStream(readPropertiesFile);
399 applicationProperties.clear();
400 applicationProperties.load(fis);
402 // remove any old build properties
404 deleteBuildProperties();
406 } catch (Exception ex)
408 System.out.println("Error reading properties file: " + ex);
412 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
413 if (getDefault("USE_PROXY", false))
415 String proxyServer = getDefault("PROXY_SERVER", ""),
416 proxyPort = getDefault("PROXY_PORT", "8080");
420 // PROXY TYPE settings (now three options "none", "false", "true", but using
421 // backward compatible strings)
422 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
423 // default to upgrading old settings
427 clearProxyProperties();
429 case PROXYTYPE_SYSTEM: // use system settings
430 resetProxyProperties();
432 case PROXYTYPE_CUSTOM: // use specified proxy settings
433 String httpHost = getDefault("PROXY_SERVER", "");
434 String httpPort = getDefault("PROXY_PORT", "8080");
435 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
436 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
437 String httpUser = getDefault("PROXY_AUTH_USER", null);
438 // https.proxyUser and https.proxyPassword are not able to be
439 // independently set in Preferences yet (or http.nonProxyHosts)
440 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
441 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
442 proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
445 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
447 Console.warn(message);
450 // LOAD THE AUTHORS FROM THE authors.props file
451 String authorDetails = resolveResourceURLFor("/authors.props");
455 if (authorDetails != null)
457 URL localJarFileURL = new URL(authorDetails);
458 InputStream in = localJarFileURL.openStream();
459 applicationProperties.load(in);
462 } catch (Exception ex)
464 System.out.println("Error reading author details: " + ex);
465 authorDetails = null;
467 if (authorDetails == null)
469 applicationProperties.remove("AUTHORS");
470 applicationProperties.remove("AUTHORFNAMES");
471 applicationProperties.remove("YEAR");
474 loadBuildProperties(false);
477 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
479 SiftsSettings.setSiftDownloadDirectory(Cache
480 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
482 SiftsSettings.setFailSafePIDThreshold(
483 Cache.getDefault("sifts_fail_safe_pid_threshold",
484 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
486 SiftsSettings.setCacheThresholdInDays(
487 Cache.getDefault("sifts_cache_threshold_in_days",
488 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
490 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
491 "https://www.jalview.org/services/identifiers"));
492 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
494 StructureImportSettings.setDefaultStructureFileFormat(
495 Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
496 StructureImportSettings
497 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
498 // StructureImportSettings
499 // .setDefaultPDBFileParser(Cache.getDefault(
500 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
502 String jnlpVersion = System.getProperty("jalview.version");
504 // jnlpVersion will be null if a latest version check for the channel needs
506 // Dont do this check if running in headless mode
508 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
509 && (System.getProperty("java.awt.headless") == null || System
510 .getProperty("java.awt.headless").equals("false")))
513 class VersionChecker extends Thread
519 String remoteBuildPropertiesUrl = Cache
520 .getAppbaseBuildProperties();
522 String orgtimeout = System
523 .getProperty("sun.net.client.defaultConnectTimeout");
524 if (orgtimeout == null)
527 System.out.println("# INFO: Setting default net timeout to "
528 + orgtimeout + " seconds.");
530 String remoteVersion = null;
531 if (remoteBuildPropertiesUrl.startsWith("http"))
535 System.setProperty("sun.net.client.defaultConnectTimeout",
538 URL url = new URL(remoteBuildPropertiesUrl);
540 BufferedReader in = new BufferedReader(
541 new InputStreamReader(url.openStream()));
543 Properties remoteBuildProperties = new Properties();
544 remoteBuildProperties.load(in);
545 remoteVersion = remoteBuildProperties.getProperty("VERSION");
546 } catch (Exception ex)
549 "Non-fatal exception when checking version at "
550 + remoteBuildPropertiesUrl + ":");
551 System.out.println(ex);
552 remoteVersion = getProperty("VERSION");
555 System.setProperty("sun.net.client.defaultConnectTimeout",
558 setProperty("LATEST_VERSION", remoteVersion);
562 VersionChecker vc = new VersionChecker();
567 if (jnlpVersion != null)
569 setProperty("LATEST_VERSION", jnlpVersion);
573 applicationProperties.remove("LATEST_VERSION");
577 // LOAD USERDEFINED COLOURS
578 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
579 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
584 * construct a resource URL for the given absolute resource pathname
586 * @param resourcePath
589 private static String resolveResourceURLFor(String resourcePath)
592 if (Platform.isJS() || !Cache.class.getProtectionDomain()
593 .getCodeSource().getLocation().toString().endsWith(".jar"))
597 url = Cache.class.getResource(resourcePath).toString();
598 } catch (Exception ex)
600 System.err.println("Failed to resolve resource " + resourcePath
601 + ": " + ex.getMessage());
606 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
607 .getLocation().toString().concat("!" + resourcePath));
612 public static void loadBuildProperties(boolean reportVersion)
614 String codeInstallation = getProperty("INSTALLATION");
615 boolean printVersion = codeInstallation == null;
618 * read build properties - from the Jalview jar for a Java distribution,
619 * or from codebase file in test or JalviewJS context
623 String buildDetails = resolveResourceURLFor("/.build_properties");
624 URL localJarFileURL = new URL(buildDetails);
625 InputStream in = localJarFileURL.openStream();
626 buildProperties.load(in);
628 if (buildProperties.getProperty("BUILD_DATE", null) != null)
630 applicationProperties.put("BUILD_DATE",
631 buildProperties.getProperty("BUILD_DATE"));
633 if (buildProperties.getProperty("INSTALLATION", null) != null)
635 applicationProperties.put("INSTALLATION",
636 buildProperties.getProperty("INSTALLATION"));
638 if (buildProperties.getProperty("VERSION", null) != null)
640 applicationProperties.put("VERSION",
641 buildProperties.getProperty("VERSION"));
643 if (buildProperties.getProperty("JAVA_COMPILE_VERSION", null) != null)
645 applicationProperties.put("JAVA_COMPILE_VERSION",
646 buildProperties.getProperty("JAVA_COMPILE_VERSION"));
648 } catch (Exception ex)
650 System.out.println("Error reading build details: " + ex);
651 applicationProperties.remove("VERSION");
653 String codeVersion = getProperty("VERSION");
654 codeInstallation = getProperty("INSTALLATION");
656 if (codeVersion == null)
658 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
659 codeVersion = "Test";
660 codeInstallation = "";
664 codeInstallation = " (" + codeInstallation + ")";
666 setProperty("VERSION", codeVersion);
667 new BuildDetails(codeVersion, null, codeInstallation);
668 if (printVersion && reportVersion)
670 System.out.println(ChannelProperties.getProperty("app_name")
671 + " Version: " + codeVersion + codeInstallation);
675 private static void deleteBuildProperties()
677 applicationProperties.remove("LATEST_VERSION");
678 applicationProperties.remove("VERSION");
679 applicationProperties.remove("AUTHORS");
680 applicationProperties.remove("AUTHORFNAMES");
681 applicationProperties.remove("YEAR");
682 applicationProperties.remove("BUILD_DATE");
683 applicationProperties.remove("INSTALLATION");
687 * Gets Jalview application property of given key. Returns null if key not
693 * @return Property value
695 public static String getProperty(String key)
697 String prop = applicationProperties.getProperty(key);
698 if (prop == null && Platform.isJS())
700 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
701 + "_" + JS_PROPERTY_PREFIX + key);
707 * These methods are used when checking if the saved preference is different
708 * to the default setting
711 public static boolean getDefault(String property, boolean def)
713 String string = getProperty(property);
716 def = Boolean.valueOf(string).booleanValue();
722 public static int getDefault(String property, int def)
724 String string = getProperty(property);
729 def = Integer.parseInt(string);
730 } catch (NumberFormatException e)
732 System.out.println("Error parsing int property '" + property
733 + "' with value '" + string + "'");
741 * Answers the value of the given property, or the supplied default value if
742 * the property is not set
744 public static String getDefault(String property, String def)
746 String value = getProperty(property);
747 return value == null ? def : value;
751 * Stores property in the file "HOME_DIR/.jalview_properties"
756 * String value of property
758 * @return previous value of property (or null)
760 public static Object setProperty(String key, String obj)
762 Object oldValue = null;
765 oldValue = applicationProperties.setProperty(key, obj);
766 if (propertiesFile != null && !propsAreReadOnly)
768 FileOutputStream out = new FileOutputStream(propertiesFile);
769 applicationProperties.store(out, "---JalviewX Properties File---");
772 } catch (Exception ex)
775 "Error setting property: " + key + " " + obj + "\n" + ex);
781 * remove the specified property from the jalview properties file
785 public static void removeProperty(String string)
787 applicationProperties.remove(string);
792 * save the properties to the jalview properties path
794 public static void saveProperties()
796 if (!propsAreReadOnly)
800 FileOutputStream out = new FileOutputStream(propertiesFile);
801 applicationProperties.store(out, "---JalviewX Properties File---");
803 } catch (Exception ex)
805 System.out.println("Error saving properties: " + ex);
811 * internal vamsas class discovery state
813 private static int vamsasJarsArePresent = -1;
816 * Searches for vamsas client classes on class path.
818 * @return true if vamsas client is present on classpath
820 public static boolean vamsasJarsPresent()
822 if (vamsasJarsArePresent == -1)
826 if (jalview.jbgui.GDesktop.class.getClassLoader()
827 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
830 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
831 vamsasJarsArePresent = 1;
832 JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
833 Console.getCachedLogLevel("logs.Vamsas.Level"));
834 JLoggerLog4j.addAppender(lvclient, Console.log,
835 JALVIEW_LOGGER_NAME);
836 // Tell the user that debug is enabled
837 lvclient.debug(ChannelProperties.getProperty("app_name")
838 + " Vamsas Client Debugging Output Follows.");
840 } catch (Exception e)
842 vamsasJarsArePresent = 0;
843 Console.debug("Vamsas Classes are not present");
846 return (vamsasJarsArePresent > 0);
850 * internal vamsas class discovery state
852 private static int groovyJarsArePresent = -1;
855 * Searches for vamsas client classes on class path.
857 * @return true if vamsas client is present on classpath
859 public static boolean groovyJarsPresent()
861 if (groovyJarsArePresent == -1)
865 if (Cache.class.getClassLoader()
866 .loadClass("groovy.lang.GroovyObject") != null)
869 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
870 groovyJarsArePresent = 1;
871 JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
872 Console.getCachedLogLevel("logs.Groovy.Level"));
873 JLoggerLog4j.addAppender(lgclient, Console.log,
874 JALVIEW_LOGGER_NAME);
875 // Tell the user that debug is enabled
876 lgclient.debug(ChannelProperties.getProperty("app_name")
877 + " Groovy Client Debugging Output Follows.");
881 groovyJarsArePresent = 0;
882 Console.debug("Groovy Classes are not present", e);
883 } catch (Exception e)
885 groovyJarsArePresent = 0;
886 Console.debug("Groovy Classes are not present");
889 return (groovyJarsArePresent > 0);
893 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
896 protected static Object tracker = null;
898 protected static Class trackerfocus = null;
900 protected static Class jgoogleanalyticstracker = null;
903 * Initialise the google tracker if it is not done already.
905 public static void initGoogleTracker()
909 if (jgoogleanalyticstracker == null)
911 // try to get the tracker class
914 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
915 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
916 trackerfocus = Cache.class.getClassLoader()
917 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
918 } catch (Exception e)
921 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
923 jgoogleanalyticstracker = null;
928 // now initialise tracker
929 Exception re = null, ex = null;
931 String vrs = "No Version Accessible";
934 // Google analytics tracking code for Library Finder
935 tracker = jgoogleanalyticstracker
936 .getConstructor(new Class[]
937 { String.class, String.class, String.class })
938 .newInstance(new Object[]
939 { ChannelProperties.getProperty("app_name") + " Desktop",
940 (vrs = Cache.getProperty("VERSION") + "_"
941 + Cache.getDefault("BUILD_DATE", "unknown")),
943 jgoogleanalyticstracker
944 .getMethod("trackAsynchronously", new Class[]
946 .invoke(tracker, new Object[]
947 { trackerfocus.getConstructor(new Class[] { String.class })
948 .newInstance(new Object[]
949 { "Application Started." }) });
950 } catch (RuntimeException e)
953 } catch (Exception e)
960 if (re != null || ex != null || err != null)
964 Console.debug("Caught runtime exception in googletracker init:",
970 "Failed to initialise GoogleTracker for Jalview Desktop with version "
977 "Whilst initing GoogleTracker for Jalview Desktop version "
984 Console.debug("Successfully initialised tracker.");
990 * get the user's default colour if available
996 public static Color getDefaultColour(String property, Color defcolour)
998 String colprop = getProperty(property);
1003 Color col = ColorUtils.parseColourString(colprop);
1006 Console.warn("Couldn't parse '" + colprop + "' as a colour for "
1009 return (col == null) ? defcolour : col;
1013 * store a colour as a Jalview user default property
1018 public static void setColourProperty(String property, Color colour)
1020 setProperty(property, jalview.util.Format.getHexString(colour));
1024 * Stores a formatted date in a jalview property, using a fixed locale.
1026 * @param propertyName
1028 * @return the formatted date string
1030 public static String setDateProperty(String propertyName, Date date)
1032 String formatted = date_format.format(date);
1033 setProperty(propertyName, formatted);
1038 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1039 * format) and returns as a Date, or null if parsing fails
1041 * @param propertyName
1045 public static Date getDateProperty(String propertyName)
1047 String val = getProperty(propertyName);
1052 return date_format.parse(val);
1053 } catch (Exception ex)
1055 System.err.println("Invalid or corrupt date in property '"
1056 + propertyName + "' : value was '" + val + "'");
1063 * get and parse a property as an integer. send any parsing problems to
1067 * @return null or Integer
1069 public static Integer getIntegerProperty(String property)
1071 String val = getProperty(property);
1072 if (val != null && (val = val.trim()).length() > 0)
1076 return Integer.valueOf(val);
1077 } catch (NumberFormatException x)
1079 System.err.println("Invalid integer in property '" + property
1080 + "' (value was '" + val + "')");
1087 * Set the specified value, or remove it if null or empty. Does not save the
1093 public static void setOrRemove(String propName, String value)
1095 if (propName == null)
1099 if (value == null || value.trim().length() < 1)
1101 Cache.applicationProperties.remove(propName);
1105 Cache.applicationProperties.setProperty(propName, value);
1110 * Loads in user colour schemes from files.
1113 * a '|'-delimited list of file paths
1115 public static void initUserColourSchemes(String files)
1117 if (files == null || files.length() == 0)
1122 // In case colours can't be loaded, we'll remove them
1123 // from the default list here.
1124 StringBuffer coloursFound = new StringBuffer();
1125 StringTokenizer st = new StringTokenizer(files, "|");
1126 while (st.hasMoreElements())
1128 String file = st.nextToken();
1131 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1134 if (coloursFound.length() > 0)
1136 coloursFound.append("|");
1138 coloursFound.append(file);
1139 ColourSchemes.getInstance().registerColourScheme(ucs);
1141 } catch (Exception ex)
1143 System.out.println("Error loading User ColourFile\n" + ex);
1146 if (!files.equals(coloursFound.toString()))
1148 if (coloursFound.toString().length() > 1)
1150 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1151 coloursFound.toString());
1155 applicationProperties
1156 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1162 * Initial logging information helper for various versions output
1166 * @param defaultValue
1168 private static void appendIfNotNull(StringBuilder sb, String prefix,
1169 String value, String suffix, String defaultValue)
1171 if (value == null && defaultValue == null)
1177 sb.append(value == null ? defaultValue : value);
1184 * @return Jalview version, build details and JVM platform version for console
1186 public static String getVersionDetailsForConsole()
1188 StringBuilder sb = new StringBuilder();
1189 sb.append(ChannelProperties.getProperty("app_name"))
1190 .append(" Version: ");
1191 sb.append(Cache.getDefault("VERSION", "TEST"));
1193 sb.append(ChannelProperties.getProperty("app_name"))
1194 .append(" Installation: ");
1195 sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1197 sb.append("Build Date: ");
1198 sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1200 sb.append("Java version: ");
1201 sb.append(System.getProperty("java.version"));
1203 sb.append(System.getProperty("os.arch"));
1205 sb.append(System.getProperty("os.name"));
1207 sb.append(System.getProperty("os.version"));
1209 appendIfNotNull(sb, "Install4j version: ",
1210 System.getProperty("sys.install4jVersion"), "\n", null);
1211 appendIfNotNull(sb, "Install4j template version: ",
1212 System.getProperty("installer_template_version"), "\n", null);
1213 appendIfNotNull(sb, "Launcher version: ",
1214 System.getProperty("launcher_version"), "\n", null);
1215 LookAndFeel laf = UIManager.getLookAndFeel();
1216 String lafName = laf == null ? "Not obtained" : laf.getName();
1217 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1218 sb.append("LookAndFeel: ");
1221 sb.append(lafClass);
1223 if (Console.isDebugEnabled()
1224 || !"release".equals(ChannelProperties.getProperty("channel")))
1226 appendIfNotNull(sb, "Channel: ",
1227 ChannelProperties.getProperty("channel"), "\n", null);
1228 appendIfNotNull(sb, "Getdown appdir: ",
1229 System.getProperty("getdowninstanceappdir"), "\n", null);
1230 appendIfNotNull(sb, "Getdown appbase: ",
1231 System.getProperty("getdowninstanceappbase"), "\n", null);
1232 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1235 return sb.toString();
1240 * @return build details as reported in splashscreen
1242 public static String getBuildDetailsForSplash()
1244 // consider returning more human friendly info
1245 // eg 'built from Source' or update channel
1246 return Cache.getDefault("INSTALLATION", "unknown");
1249 public static String getStackTraceString(Throwable t)
1251 StringWriter sw = new StringWriter();
1252 PrintWriter pw = new PrintWriter(sw);
1253 t.printStackTrace(pw);
1254 return sw.toString();
1257 // proxy properties methods
1258 public static void clearProxyProperties()
1260 setProxyProperties(null, null, null, null, null, null, null, null,
1264 public static void resetProxyProperties()
1266 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1267 startupProxyProperties[2], startupProxyProperties[3],
1268 startupProxyProperties[4],
1269 startupProxyProperties[5] == null ? null
1270 : startupProxyProperties[5].toCharArray(),
1271 startupProxyProperties[6],
1272 startupProxyProperties[7] == null ? null
1273 : startupProxyProperties[7].toCharArray(),
1274 startupProxyProperties[8]);
1275 StringBuilder sb = new StringBuilder();
1276 sb.append("Setting proxy properties to: http.proxyHost=")
1277 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1278 .append(startupProxyProperties[1])
1279 .append(startupProxyProperties[4] != null
1280 && !startupProxyProperties[4].isEmpty()
1281 ? " [" + startupProxyProperties[4] + "]"
1283 .append(", https.proxyHost=").append(startupProxyProperties[2])
1284 .append(", https.proxyPort=").append(startupProxyProperties[3])
1285 .append(startupProxyProperties[6] != null
1286 && !startupProxyProperties[6].isEmpty()
1287 ? " [" + startupProxyProperties[6] + "]"
1290 Console.debug(sb.toString());
1293 public static void setProxyPropertiesFromPreferences()
1295 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1298 public static void setProxyPropertiesFromPreferences(
1299 String previousProxyType)
1301 String proxyType = Cache.getDefault("USE_PROXY",
1302 Cache.PROXYTYPE_SYSTEM);
1303 if (previousProxyType != null
1304 && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1306 && proxyType.equals(previousProxyType))
1313 case Cache.PROXYTYPE_NONE:
1314 if (!previousProxyType.equals(proxyType))
1316 Console.info("Setting no proxy settings");
1317 Cache.setProxyProperties(null, null, null, null, null, null, null,
1321 case Cache.PROXYTYPE_CUSTOM:
1322 // always re-set a custom proxy -- it might have changed, particularly
1324 Console.info("Setting custom proxy settings");
1325 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1326 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1327 Cache.getDefault("PROXY_PORT", null),
1328 Cache.getDefault("PROXY_SERVER_HTTPS", null),
1329 Cache.getDefault("PROXY_PORT_HTTPS", null),
1330 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1332 proxyAuthSet ? Cache.proxyAuthPassword : null,
1333 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1335 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1337 default: // system proxy settings by default
1338 Console.info("Setting system proxy settings");
1339 Cache.resetProxyProperties();
1343 public static void setProxyProperties(String httpHost, String httpPort,
1344 String httpsHost, String httpsPort, String httpUser,
1345 char[] httpPassword, String httpsUser, char[] httpsPassword,
1346 String nonProxyHosts)
1348 setOrClearSystemProperty("http.proxyHost", httpHost);
1349 setOrClearSystemProperty("http.proxyPort", httpPort);
1350 setOrClearSystemProperty("https.proxyHost", httpsHost);
1351 setOrClearSystemProperty("https.proxyPort", httpsPort);
1352 setOrClearSystemProperty("http.proxyUser", httpUser);
1353 setOrClearSystemProperty("https.proxyUser", httpsUser);
1354 // note: passwords for http.proxyPassword and https.proxyPassword are sent
1355 // via the Authenticator, properties do not need to be set
1357 // are we using a custom proxy (password prompt might be required)?
1358 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1359 .equals(PROXYTYPE_CUSTOM);
1362 * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1363 * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1364 * is not re-called).
1365 * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1367 * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1369 * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1374 sun.net.www.protocol.http.AuthCacheValue
1375 .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1376 } catch (Throwable t)
1378 Cache.error(t.getMessage());
1379 Cache.debug(getStackTraceString(t));
1383 if (httpUser != null || httpsUser != null)
1387 char[] displayHttpPw = new char[httpPassword == null ? 0
1388 : httpPassword.length];
1389 Arrays.fill(displayHttpPw, '*');
1391 "CACHE Proxy: setting new Authenticator with httpUser='"
1392 + httpUser + "' httpPassword='" + displayHttpPw
1394 if (!Platform.isJS())
1396 * java.net.Authenticator not implemented in SwingJS yet
1402 Authenticator.setDefault(new Authenticator()
1405 protected PasswordAuthentication getPasswordAuthentication()
1407 if (getRequestorType() == RequestorType.PROXY)
1409 String protocol = getRequestingProtocol();
1410 boolean needProxyPasswordSet = false;
1411 if (customProxySet &&
1412 // we have a username but no password for the scheme being
1414 (protocol.equalsIgnoreCase("http")
1415 && (httpUser != null
1416 && httpUser.length() > 0
1417 && (httpPassword == null
1418 || httpPassword.length == 0)))
1419 || (protocol.equalsIgnoreCase("https")
1420 && (httpsUser != null
1421 && httpsUser.length() > 0
1422 && (httpsPassword == null
1423 || httpsPassword.length == 0))))
1425 // open Preferences -> Connections
1426 String message = MessageManager
1427 .getString("label.proxy_password_required");
1428 Preferences.openPreferences(
1429 Preferences.TabRef.CONNECTIONS_TAB, message);
1430 Preferences.getInstance()
1431 .proxyAuthPasswordCheckHighlight(true, true);
1437 if (protocol.equalsIgnoreCase("http")
1438 && getRequestingHost()
1439 .equalsIgnoreCase(httpHost)
1440 && getRequestingPort() == Integer
1444 "AUTHENTICATOR returning PasswordAuthentication(\""
1445 + httpUser + "\", '"
1446 + new String(displayHttpPw) + "')");
1447 return new PasswordAuthentication(httpUser,
1450 if (protocol.equalsIgnoreCase("https")
1451 && getRequestingHost()
1452 .equalsIgnoreCase(httpsHost)
1453 && getRequestingPort() == Integer
1454 .valueOf(httpsPort))
1456 char[] displayHttpsPw = new char[httpPassword.length];
1457 Arrays.fill(displayHttpsPw, '*');
1459 "AUTHENTICATOR returning PasswordAuthentication(\""
1460 + httpsUser + "\", '" + displayHttpsPw
1462 return new PasswordAuthentication(httpsUser,
1465 } catch (NumberFormatException e)
1467 Console.error("Problem with proxy port values [http:"
1468 + httpPort + ", https:" + httpsPort + "]");
1471 "AUTHENTICATOR after trying to get PasswordAuthentication");
1474 // non proxy request
1475 Console.debug("AUTHENTICATOR returning null");
1479 } // end of j2sIgnore for java.net.Authenticator
1481 // required to re-enable basic authentication (should be okay for a
1484 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1485 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1486 } catch (SecurityException e)
1488 Console.error("Could not set default Authenticator");
1489 Console.debug(getStackTraceString(e));
1494 // reset the Authenticator to protect http.proxyUser and
1495 // http.proxyPassword Just In Case
1496 /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1497 * has working credentials. No workaround for Java 11.
1499 if (!Platform.isJS())
1501 * java.net.Authenticator not implemented in SwingJS yet
1508 "AUTHENTICATOR setting default Authenticator to null");
1509 Authenticator.setDefault(null);
1513 // nonProxyHosts not currently configurable in Preferences
1515 "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1516 + nonProxyHosts + "\"");
1517 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1520 public static void setOrClearSystemProperty(String key, char[] value)
1522 setOrClearSystemProperty(key,
1523 (value == null) ? null : new String(value));
1526 public static void setOrClearSystemProperty(String key, String value)
1534 System.clearProperty(key);
1538 System.setProperty(key, value);
1543 * Getdown appbase methods
1546 private static final String releaseAppbase;
1548 private static String getdownAppbase;
1550 private static String getdownDistDir;
1554 if (!Platform.isJS())
1556 Float specversion = Float
1557 .parseFloat(System.getProperty("java.specification.version"));
1558 releaseAppbase = (specversion < 9)
1559 ? "https://www.jalview.org/getdown/release/1.8"
1560 : "https://www.jalview.org/getdown/release/11";
1564 // this value currenly made up, can be changed to URL that will be
1565 // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1566 releaseAppbase = "https://www.jalview.org/jalview-js";
1567 getdownAppbase = releaseAppbase;
1568 getdownDistDir = "/swingjs/j2s";
1572 // look for properties (passed in by getdown) otherwise default to release
1573 private static void setGetdownAppbase()
1575 if (getdownAppbase != null)
1579 String appbase = System.getProperty("getdownappbase");
1580 String distDir = System.getProperty("getdowndistdir");
1581 if (appbase == null)
1583 appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1584 distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1586 if (appbase == null)
1588 appbase = releaseAppbase;
1589 distDir = "release";
1591 if (appbase.endsWith("/"))
1593 appbase = appbase.substring(0, appbase.length() - 1);
1595 if (distDir == null)
1597 distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1599 getdownAppbase = appbase;
1600 getdownDistDir = distDir;
1603 public static String getGetdownAppbase()
1605 setGetdownAppbase();
1606 return getdownAppbase;
1609 public static String getAppbaseBuildProperties()
1611 String appbase = getGetdownAppbase();
1612 return appbase + "/" + getdownDistDir + "/build_properties";