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;
523 System.setProperty("sun.net.client.defaultConnectTimeout",
525 java.net.URL url = new java.net.URL(remoteBuildPropertiesUrl);
527 BufferedReader in = new BufferedReader(
528 new InputStreamReader(url.openStream()));
530 Properties remoteBuildProperties = new Properties();
531 remoteBuildProperties.load(in);
532 remoteVersion = remoteBuildProperties.getProperty("VERSION");
533 } catch (Exception ex)
536 .println("Non-fatal exception when checking version at "
537 + remoteBuildPropertiesUrl + ":");
538 System.out.println(ex);
539 remoteVersion = getProperty("VERSION");
541 System.setProperty("sun.net.client.defaultConnectTimeout",
544 setProperty("LATEST_VERSION", remoteVersion);
548 VersionChecker vc = new VersionChecker();
553 if (jnlpVersion != null)
555 setProperty("LATEST_VERSION", jnlpVersion);
559 applicationProperties.remove("LATEST_VERSION");
563 // LOAD USERDEFINED COLOURS
564 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
565 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
570 * construct a resource URL for the given absolute resource pathname
572 * @param resourcePath
575 private static String resolveResourceURLFor(String resourcePath)
578 if (Platform.isJS() || !Cache.class.getProtectionDomain()
579 .getCodeSource().getLocation().toString().endsWith(".jar"))
583 url = Cache.class.getResource(resourcePath).toString();
584 } catch (Exception ex)
586 System.err.println("Failed to resolve resource " + resourcePath
587 + ": " + ex.getMessage());
592 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
593 .getLocation().toString().concat("!" + resourcePath));
598 public static void loadBuildProperties(boolean reportVersion)
600 String codeInstallation = getProperty("INSTALLATION");
601 boolean printVersion = codeInstallation == null;
604 * read build properties - from the Jalview jar for a Java distribution,
605 * or from codebase file in test or JalviewJS context
609 String buildDetails = resolveResourceURLFor("/.build_properties");
610 URL localJarFileURL = new URL(buildDetails);
611 InputStream in = localJarFileURL.openStream();
612 buildProperties.load(in);
614 if (buildProperties.getProperty("BUILD_DATE", null) != null)
616 applicationProperties.put("BUILD_DATE",
617 buildProperties.getProperty("BUILD_DATE"));
619 if (buildProperties.getProperty("INSTALLATION", null) != null)
621 applicationProperties.put("INSTALLATION",
622 buildProperties.getProperty("INSTALLATION"));
624 if (buildProperties.getProperty("VERSION", null) != null)
626 applicationProperties.put("VERSION",
627 buildProperties.getProperty("VERSION"));
629 } catch (Exception ex)
631 System.out.println("Error reading build details: " + ex);
632 applicationProperties.remove("VERSION");
634 String codeVersion = getProperty("VERSION");
635 codeInstallation = getProperty("INSTALLATION");
637 if (codeVersion == null)
639 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
640 codeVersion = "Test";
641 codeInstallation = "";
645 codeInstallation = " (" + codeInstallation + ")";
647 setProperty("VERSION", codeVersion);
648 new BuildDetails(codeVersion, null, codeInstallation);
649 if (printVersion && reportVersion)
651 System.out.println(ChannelProperties.getProperty("app_name")
652 + " Version: " + codeVersion + codeInstallation);
656 private static void deleteBuildProperties()
658 applicationProperties.remove("LATEST_VERSION");
659 applicationProperties.remove("VERSION");
660 applicationProperties.remove("AUTHORS");
661 applicationProperties.remove("AUTHORFNAMES");
662 applicationProperties.remove("YEAR");
663 applicationProperties.remove("BUILD_DATE");
664 applicationProperties.remove("INSTALLATION");
668 * Gets Jalview application property of given key. Returns null if key not
674 * @return Property value
676 public static String getProperty(String key)
678 String prop = applicationProperties.getProperty(key);
679 if (prop == null && Platform.isJS())
681 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
682 + "_" + JS_PROPERTY_PREFIX + key);
688 * These methods are used when checking if the saved preference is different
689 * to the default setting
692 public static boolean getDefault(String property, boolean def)
694 String string = getProperty(property);
697 def = Boolean.valueOf(string).booleanValue();
703 public static int getDefault(String property, int def)
705 String string = getProperty(property);
710 def = Integer.parseInt(string);
711 } catch (NumberFormatException e)
713 System.out.println("Error parsing int property '" + property
714 + "' with value '" + string + "'");
722 * Answers the value of the given property, or the supplied default value if
723 * the property is not set
725 public static String getDefault(String property, String def)
727 String value = getProperty(property);
728 return value == null ? def : value;
732 * Stores property in the file "HOME_DIR/.jalview_properties"
737 * String value of property
739 * @return previous value of property (or null)
741 public static Object setProperty(String key, String obj)
743 Object oldValue = null;
746 oldValue = applicationProperties.setProperty(key, obj);
747 if (propertiesFile != null && !propsAreReadOnly)
749 FileOutputStream out = new FileOutputStream(propertiesFile);
750 applicationProperties.store(out, "---JalviewX Properties File---");
753 } catch (Exception ex)
756 "Error setting property: " + key + " " + obj + "\n" + ex);
762 * remove the specified property from the jalview properties file
766 public static void removeProperty(String string)
768 applicationProperties.remove(string);
773 * save the properties to the jalview properties path
775 public static void saveProperties()
777 if (!propsAreReadOnly)
781 FileOutputStream out = new FileOutputStream(propertiesFile);
782 applicationProperties.store(out, "---JalviewX Properties File---");
784 } catch (Exception ex)
786 System.out.println("Error saving properties: " + ex);
792 * internal vamsas class discovery state
794 private static int vamsasJarsArePresent = -1;
797 * Searches for vamsas client classes on class path.
799 * @return true if vamsas client is present on classpath
801 public static boolean vamsasJarsPresent()
803 if (vamsasJarsArePresent == -1)
807 if (jalview.jbgui.GDesktop.class.getClassLoader()
808 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
811 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
812 vamsasJarsArePresent = 1;
813 JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
814 Console.getCachedLogLevel("logs.Vamsas.Level"));
815 JLoggerLog4j.addAppender(lvclient, Console.log,
816 JALVIEW_LOGGER_NAME);
817 // Tell the user that debug is enabled
818 lvclient.debug(ChannelProperties.getProperty("app_name")
819 + " Vamsas Client Debugging Output Follows.");
821 } catch (Exception e)
823 vamsasJarsArePresent = 0;
824 Console.debug("Vamsas Classes are not present");
827 return (vamsasJarsArePresent > 0);
831 * internal vamsas class discovery state
833 private static int groovyJarsArePresent = -1;
836 * Searches for vamsas client classes on class path.
838 * @return true if vamsas client is present on classpath
840 public static boolean groovyJarsPresent()
842 if (groovyJarsArePresent == -1)
846 if (Cache.class.getClassLoader()
847 .loadClass("groovy.lang.GroovyObject") != null)
850 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
851 groovyJarsArePresent = 1;
852 JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
853 Console.getCachedLogLevel("logs.Groovy.Level"));
854 JLoggerLog4j.addAppender(lgclient, Console.log,
855 JALVIEW_LOGGER_NAME);
856 // Tell the user that debug is enabled
857 lgclient.debug(ChannelProperties.getProperty("app_name")
858 + " Groovy Client Debugging Output Follows.");
862 groovyJarsArePresent = 0;
863 Console.debug("Groovy Classes are not present", e);
864 } catch (Exception e)
866 groovyJarsArePresent = 0;
867 Console.debug("Groovy Classes are not present");
870 return (groovyJarsArePresent > 0);
874 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
877 protected static Object tracker = null;
879 protected static Class trackerfocus = null;
881 protected static Class jgoogleanalyticstracker = null;
884 * Initialise the google tracker if it is not done already.
886 public static void initGoogleTracker()
890 if (jgoogleanalyticstracker == null)
892 // try to get the tracker class
895 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
896 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
897 trackerfocus = Cache.class.getClassLoader()
898 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
899 } catch (Exception e)
902 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
904 jgoogleanalyticstracker = null;
909 // now initialise tracker
910 Exception re = null, ex = null;
912 String vrs = "No Version Accessible";
915 // Google analytics tracking code for Library Finder
916 tracker = jgoogleanalyticstracker
917 .getConstructor(new Class[]
918 { String.class, String.class, String.class })
919 .newInstance(new Object[]
920 { ChannelProperties.getProperty("app_name") + " Desktop",
921 (vrs = Cache.getProperty("VERSION") + "_"
922 + Cache.getDefault("BUILD_DATE", "unknown")),
924 jgoogleanalyticstracker
925 .getMethod("trackAsynchronously", new Class[]
927 .invoke(tracker, new Object[]
928 { trackerfocus.getConstructor(new Class[] { String.class })
929 .newInstance(new Object[]
930 { "Application Started." }) });
931 } catch (RuntimeException e)
934 } catch (Exception e)
941 if (re != null || ex != null || err != null)
945 Console.debug("Caught runtime exception in googletracker init:",
951 "Failed to initialise GoogleTracker for Jalview Desktop with version "
958 "Whilst initing GoogleTracker for Jalview Desktop version "
965 Console.debug("Successfully initialised tracker.");
971 * get the user's default colour if available
977 public static Color getDefaultColour(String property, Color defcolour)
979 String colprop = getProperty(property);
984 Color col = ColorUtils.parseColourString(colprop);
987 Console.warn("Couldn't parse '" + colprop + "' as a colour for "
990 return (col == null) ? defcolour : col;
994 * store a colour as a Jalview user default property
999 public static void setColourProperty(String property, Color colour)
1001 setProperty(property, jalview.util.Format.getHexString(colour));
1005 * Stores a formatted date in a jalview property, using a fixed locale.
1007 * @param propertyName
1009 * @return the formatted date string
1011 public static String setDateProperty(String propertyName, Date date)
1013 String formatted = date_format.format(date);
1014 setProperty(propertyName, formatted);
1019 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1020 * format) and returns as a Date, or null if parsing fails
1022 * @param propertyName
1026 public static Date getDateProperty(String propertyName)
1028 String val = getProperty(propertyName);
1033 return date_format.parse(val);
1034 } catch (Exception ex)
1036 System.err.println("Invalid or corrupt date in property '"
1037 + propertyName + "' : value was '" + val + "'");
1044 * get and parse a property as an integer. send any parsing problems to
1048 * @return null or Integer
1050 public static Integer getIntegerProperty(String property)
1052 String val = getProperty(property);
1053 if (val != null && (val = val.trim()).length() > 0)
1057 return Integer.valueOf(val);
1058 } catch (NumberFormatException x)
1060 System.err.println("Invalid integer in property '" + property
1061 + "' (value was '" + val + "')");
1068 * Set the specified value, or remove it if null or empty. Does not save the
1074 public static void setOrRemove(String propName, String value)
1076 if (propName == null)
1080 if (value == null || value.trim().length() < 1)
1082 Cache.applicationProperties.remove(propName);
1086 Cache.applicationProperties.setProperty(propName, value);
1091 * Loads in user colour schemes from files.
1094 * a '|'-delimited list of file paths
1096 public static void initUserColourSchemes(String files)
1098 if (files == null || files.length() == 0)
1103 // In case colours can't be loaded, we'll remove them
1104 // from the default list here.
1105 StringBuffer coloursFound = new StringBuffer();
1106 StringTokenizer st = new StringTokenizer(files, "|");
1107 while (st.hasMoreElements())
1109 String file = st.nextToken();
1112 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1115 if (coloursFound.length() > 0)
1117 coloursFound.append("|");
1119 coloursFound.append(file);
1120 ColourSchemes.getInstance().registerColourScheme(ucs);
1122 } catch (Exception ex)
1124 System.out.println("Error loading User ColourFile\n" + ex);
1127 if (!files.equals(coloursFound.toString()))
1129 if (coloursFound.toString().length() > 1)
1131 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1132 coloursFound.toString());
1136 applicationProperties
1137 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1143 * Initial logging information helper for various versions output
1147 * @param defaultValue
1149 private static void appendIfNotNull(StringBuilder sb, String prefix,
1150 String value, String suffix, String defaultValue)
1152 if (value == null && defaultValue == null)
1158 sb.append(value == null ? defaultValue : value);
1165 * @return Jalview version, build details and JVM platform version for console
1167 public static String getVersionDetailsForConsole()
1169 StringBuilder sb = new StringBuilder();
1170 sb.append(ChannelProperties.getProperty("app_name"))
1171 .append(" Version: ");
1172 sb.append(Cache.getDefault("VERSION", "TEST"));
1174 sb.append(ChannelProperties.getProperty("app_name"))
1175 .append(" Installation: ");
1176 sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1178 sb.append("Build Date: ");
1179 sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1181 sb.append("Java version: ");
1182 sb.append(System.getProperty("java.version"));
1184 sb.append(System.getProperty("os.arch"));
1186 sb.append(System.getProperty("os.name"));
1188 sb.append(System.getProperty("os.version"));
1190 appendIfNotNull(sb, "Install4j version: ",
1191 System.getProperty("sys.install4jVersion"), "\n", null);
1192 appendIfNotNull(sb, "Install4j template version: ",
1193 System.getProperty("installer_template_version"), "\n", null);
1194 appendIfNotNull(sb, "Launcher version: ",
1195 System.getProperty("launcher_version"), "\n", null);
1196 LookAndFeel laf = UIManager.getLookAndFeel();
1197 String lafName = laf == null ? "Not obtained" : laf.getName();
1198 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1199 sb.append("LookAndFeel: ");
1202 sb.append(lafClass);
1204 if (Console.isDebugEnabled()
1205 || !"release".equals(ChannelProperties.getProperty("channel")))
1207 appendIfNotNull(sb, "Channel: ",
1208 ChannelProperties.getProperty("channel"), "\n", null);
1209 appendIfNotNull(sb, "Getdown appdir: ",
1210 System.getProperty("getdownappdir"), "\n", null);
1211 appendIfNotNull(sb, "Getdown appbase: ",
1212 System.getProperty("getdownappbase"), "\n", null);
1213 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1216 return sb.toString();
1221 * @return build details as reported in splashscreen
1223 public static String getBuildDetailsForSplash()
1225 // consider returning more human friendly info
1226 // eg 'built from Source' or update channel
1227 return Cache.getDefault("INSTALLATION", "unknown");
1230 public static String getStackTraceString(Throwable t)
1232 StringWriter sw = new StringWriter();
1233 PrintWriter pw = new PrintWriter(sw);
1234 t.printStackTrace(pw);
1235 return sw.toString();
1238 // proxy properties methods
1239 public static void clearProxyProperties()
1241 setProxyProperties(null, null, null, null, null, null, null, null,
1245 public static void resetProxyProperties()
1247 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1248 startupProxyProperties[2], startupProxyProperties[3],
1249 startupProxyProperties[4],
1250 startupProxyProperties[5] == null ? null
1251 : startupProxyProperties[5].toCharArray(),
1252 startupProxyProperties[6],
1253 startupProxyProperties[7] == null ? null
1254 : startupProxyProperties[7].toCharArray(),
1255 startupProxyProperties[8]);
1256 StringBuilder sb = new StringBuilder();
1257 sb.append("Setting proxy properties to: http.proxyHost=")
1258 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1259 .append(startupProxyProperties[1])
1260 .append(startupProxyProperties[4] != null
1261 && !startupProxyProperties[4].isEmpty()
1262 ? " [" + startupProxyProperties[4] + "]"
1264 .append(", https.proxyHost=").append(startupProxyProperties[2])
1265 .append(", https.proxyPort=").append(startupProxyProperties[3])
1266 .append(startupProxyProperties[6] != null
1267 && !startupProxyProperties[6].isEmpty()
1268 ? " [" + startupProxyProperties[6] + "]"
1271 Console.debug(sb.toString());
1274 public static void setProxyPropertiesFromPreferences()
1276 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1279 public static void setProxyPropertiesFromPreferences(
1280 String previousProxyType)
1282 String proxyType = Cache.getDefault("USE_PROXY",
1283 Cache.PROXYTYPE_SYSTEM);
1284 if (previousProxyType != null
1285 && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1287 && proxyType.equals(previousProxyType))
1294 case Cache.PROXYTYPE_NONE:
1295 if (!previousProxyType.equals(proxyType))
1297 Console.info("Setting no proxy settings");
1298 Cache.setProxyProperties(null, null, null, null, null, null, null,
1302 case Cache.PROXYTYPE_CUSTOM:
1303 // always re-set a custom proxy -- it might have changed, particularly
1305 Console.info("Setting custom proxy settings");
1306 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1307 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1308 Cache.getDefault("PROXY_PORT", null),
1309 Cache.getDefault("PROXY_SERVER_HTTPS", null),
1310 Cache.getDefault("PROXY_PORT_HTTPS", null),
1311 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1313 proxyAuthSet ? Cache.proxyAuthPassword : null,
1314 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1316 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1318 default: // system proxy settings by default
1319 Console.info("Setting system proxy settings");
1320 Cache.resetProxyProperties();
1324 public static void setProxyProperties(String httpHost, String httpPort,
1325 String httpsHost, String httpsPort, String httpUser,
1326 char[] httpPassword, String httpsUser, char[] httpsPassword,
1327 String nonProxyHosts)
1329 setOrClearSystemProperty("http.proxyHost", httpHost);
1330 setOrClearSystemProperty("http.proxyPort", httpPort);
1331 setOrClearSystemProperty("https.proxyHost", httpsHost);
1332 setOrClearSystemProperty("https.proxyPort", httpsPort);
1333 setOrClearSystemProperty("http.proxyUser", httpUser);
1334 setOrClearSystemProperty("https.proxyUser", httpsUser);
1335 // note: passwords for http.proxyPassword and https.proxyPassword are sent
1336 // via the Authenticator, properties do not need to be set
1338 // are we using a custom proxy (password prompt might be required)?
1339 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1340 .equals(PROXYTYPE_CUSTOM);
1343 * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1344 * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1345 * is not re-called).
1346 * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1348 * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1350 * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1355 sun.net.www.protocol.http.AuthCacheValue
1356 .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1357 } catch (Throwable t)
1359 Cache.error(t.getMessage());
1360 Cache.debug(getStackTraceString(t));
1364 if (httpUser != null || httpsUser != null)
1368 char[] displayHttpPw = new char[httpPassword == null ? 0
1369 : httpPassword.length];
1370 Arrays.fill(displayHttpPw, '*');
1372 "CACHE Proxy: setting new Authenticator with httpUser='"
1373 + httpUser + "' httpPassword='" + displayHttpPw
1375 if (!Platform.isJS())
1377 * java.net.Authenticator not implemented in SwingJS yet
1383 Authenticator.setDefault(new Authenticator()
1386 protected PasswordAuthentication getPasswordAuthentication()
1388 if (getRequestorType() == RequestorType.PROXY)
1390 String protocol = getRequestingProtocol();
1391 boolean needProxyPasswordSet = false;
1392 if (customProxySet &&
1393 // we have a username but no password for the scheme being
1395 (protocol.equalsIgnoreCase("http")
1396 && (httpUser != null && httpUser.length() > 0
1397 && (httpPassword == null
1398 || httpPassword.length == 0)))
1399 || (protocol.equalsIgnoreCase("https")
1400 && (httpsUser != null
1401 && httpsUser.length() > 0
1402 && (httpsPassword == null
1403 || httpsPassword.length == 0))))
1405 // open Preferences -> Connections
1406 String message = MessageManager
1407 .getString("label.proxy_password_required");
1408 Preferences.openPreferences(
1409 Preferences.TabRef.CONNECTIONS_TAB, message);
1410 Preferences.getInstance()
1411 .proxyAuthPasswordCheckHighlight(true, true);
1417 if (protocol.equalsIgnoreCase("http")
1418 && getRequestingHost()
1419 .equalsIgnoreCase(httpHost)
1420 && getRequestingPort() == Integer
1424 "AUTHENTICATOR returning PasswordAuthentication(\""
1425 + httpUser + "\", '"
1426 + new String(displayHttpPw) + "')");
1427 return new PasswordAuthentication(httpUser,
1430 if (protocol.equalsIgnoreCase("https")
1431 && getRequestingHost()
1432 .equalsIgnoreCase(httpsHost)
1433 && getRequestingPort() == Integer
1434 .valueOf(httpsPort))
1436 char[] displayHttpsPw = new char[httpPassword.length];
1437 Arrays.fill(displayHttpsPw, '*');
1439 "AUTHENTICATOR returning PasswordAuthentication(\""
1440 + httpsUser + "\", '" + displayHttpsPw
1442 return new PasswordAuthentication(httpsUser,
1445 } catch (NumberFormatException e)
1447 Console.error("Problem with proxy port values [http:"
1448 + httpPort + ", https:" + httpsPort + "]");
1451 "AUTHENTICATOR after trying to get PasswordAuthentication");
1454 // non proxy request
1455 Console.debug("AUTHENTICATOR returning null");
1459 } // end of j2sIgnore for java.net.Authenticator
1461 // required to re-enable basic authentication (should be okay for a
1464 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1465 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1466 } catch (SecurityException e)
1468 Console.error("Could not set default Authenticator");
1469 Console.debug(getStackTraceString(e));
1474 // reset the Authenticator to protect http.proxyUser and
1475 // http.proxyPassword Just In Case
1476 /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1477 * has working credentials. No workaround for Java 11.
1479 if (!Platform.isJS())
1481 * java.net.Authenticator not implemented in SwingJS yet
1488 "AUTHENTICATOR setting default Authenticator to null");
1489 Authenticator.setDefault(null);
1493 // nonProxyHosts not currently configurable in Preferences
1495 "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1496 + nonProxyHosts + "\"");
1497 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1500 public static void setOrClearSystemProperty(String key, char[] value)
1502 setOrClearSystemProperty(key,
1503 (value == null) ? null : new String(value));
1506 public static void setOrClearSystemProperty(String key, String value)
1514 System.clearProperty(key);
1518 System.setProperty(key, value);
1523 * Getdown appbase methods
1526 private static final String releaseAppbase;
1528 private static String getdownAppbase;
1530 private static String getdownDistDir;
1534 if (!Platform.isJS())
1536 Float specversion = Float
1537 .parseFloat(System.getProperty("java.specification.version"));
1538 releaseAppbase = (specversion < 9)
1539 ? "https://www.jalview.org/getdown/release/1.8"
1540 : "https://www.jalview.org/getdown/release/11";
1544 // this value currenly made up, can be changed to URL that will be
1545 // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1546 releaseAppbase = "https://www.jalview.org/jalview-js";
1547 getdownAppbase = releaseAppbase;
1548 getdownDistDir = "/swingjs/j2s";
1552 // look for properties (passed in by getdown) otherwise default to release
1553 private static void setGetdownAppbase()
1555 if (getdownAppbase != null)
1559 String appbase = System.getProperty("getdownappbase");
1560 String distDir = System.getProperty("getdowndistdir");
1561 if (appbase == null)
1563 appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1564 distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1566 if (appbase == null)
1568 appbase = releaseAppbase;
1569 distDir = "release";
1571 if (appbase.endsWith("/"))
1573 appbase = appbase.substring(0, appbase.length() - 1);
1575 if (distDir == null)
1577 distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1579 getdownAppbase = appbase;
1580 getdownDistDir = distDir;
1583 public static String getGetdownAppbase()
1585 setGetdownAppbase();
1586 return getdownAppbase;
1589 public static String getAppbaseBuildProperties()
1591 String appbase = getGetdownAppbase();
1592 return appbase + "/" + getdownDistDir + "/build_properties";