2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.Color;
24 import java.io.BufferedReader;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.PrintWriter;
31 import java.io.StringWriter;
32 import java.net.Authenticator;
33 import java.net.PasswordAuthentication;
35 import java.text.DateFormat;
36 import java.text.SimpleDateFormat;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.Date;
40 import java.util.Enumeration;
41 import java.util.Locale;
42 import java.util.Properties;
43 import java.util.StringTokenizer;
44 import java.util.TreeSet;
45 import java.util.regex.Pattern;
47 import javax.swing.LookAndFeel;
48 import javax.swing.UIManager;
50 import jalview.datamodel.PDBEntry;
51 import jalview.gui.Preferences;
52 import jalview.gui.UserDefinedColours;
53 import jalview.log.JLoggerLog4j;
54 import jalview.schemes.ColourSchemeLoader;
55 import jalview.schemes.ColourSchemes;
56 import jalview.schemes.UserColourScheme;
57 import jalview.structure.StructureImportSettings;
58 import jalview.urls.IdOrgSettings;
59 import jalview.util.ChannelProperties;
60 import jalview.util.ColorUtils;
61 import jalview.util.MessageManager;
62 import jalview.util.Platform;
63 import jalview.ws.sifts.SiftsSettings;
66 * Stores and retrieves Jalview Application Properties Lists and fields within
67 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
68 * are alternative values for a tag. <br>
70 * Current properties include:
73 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
74 * logging level for axis (used for web services) <br>
76 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
77 * the logging level for castor (used for serialization) <br>
79 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
81 * <li>SCREEN_WIDTH</li>
82 * <li>SCREEN_HEIGHT</li>
83 * <li>SCREEN_Y=285</li>
84 * <li>SCREEN_X=371</li>
85 * <li>SHOW_FULLSCREEN boolean</li>
86 * <li>FONT_NAME java font name for alignment text display</li>
87 * <li>FONT_SIZE size of displayed alignment text</li>
88 * <li>FONT_STYLE style of font displayed (sequence labels are always
90 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
91 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
92 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
93 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
94 * <li>SHOW_IDENTITY show percentage identity annotation</li>
95 * <li>SHOW_QUALITY show alignment quality annotation</li>
96 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
97 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
98 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
99 * LABEL_AND_SEQUENCE</li>
100 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
101 * sequence annotations</li>
102 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
103 * annotation row</li>
104 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
105 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
106 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
107 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
108 * <li>VERSION the version of the jalview build</li>
109 * <li>BUILD_DATE date of this build</li>
110 * <li>LATEST_VERSION the latest jalview version advertised on the
111 * www.jalview.org</li>
112 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
114 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
115 * suffix to file</li>
116 * <li>RECENT_URL list of recently retrieved URLs</li>
117 * <li>RECENT_FILE list of recently opened files</li>
118 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
119 * <li>PROXY_SERVER the proxy</li>
120 * <li>PROXY_PORT</li>
121 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
123 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
125 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
126 * collecting usage statistics</li>
127 * <li>SHOW_OVERVIEW boolean for overview window display</li>
128 * <li>ANTI_ALIAS boolean for smooth fonts</li>
129 * <li>RIGHT_ALIGN_IDS boolean</li>
130 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
131 * <li>PAD_GAPS boolean</li>
132 * <li>ID_ITALICS boolean</li>
133 * <li>SHOW_JV_SUFFIX</li>
134 * <li>WRAP_ALIGNMENT</li>
135 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
137 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
138 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
140 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
142 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
143 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
144 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
145 * jalview.utils.GroupURLLink for more info</li>
146 * <li>DEFAULT_BROWSER for unix</li>
147 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
149 * <li>VERSION_CHECK (true) check for the latest release version from
150 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
151 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
153 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
155 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
156 * displayed as '.'</li>
157 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
158 * order of a newly displayed tree</li>
159 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
160 * sequence ID strings before attempting retrieval from any datasource</li>
161 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
163 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
164 * in the alignment.</li>
165 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
167 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
169 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
170 * logo normalised to row height rather than histogram height.</li>
171 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
172 * respond to selections made in other alignments containing the same sequences.
174 * <li>SHOW_JWS2_SERVICES (true) when set to false, jalview will not
175 * auto-discover JABAWS services</li>
176 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
177 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
178 * warning dialog box is displayed.</li>
179 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
180 * when shading by annotation</li>
181 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
182 * when shading by annotation</li>
183 * <li>www.jalview.org (https://www.jalview.org) a property enabling all HTTP
184 * requests to be redirected to a mirror of https://www.jalview.org</li>
185 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
186 * alignment figure to accommodate even the longest sequence ID or annotation
188 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
189 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
190 * will override this).</li>
191 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
193 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
194 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
196 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
198 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
200 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
201 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
203 * <li>NONEWS - when set disables Jalview News from automatically appearing</li>
204 * <li>NOHTMLTEMPLATES - when set, the
205 * https://github.com/jalview/exporter-templates/tree/master/biojs repository is
206 * not downloaded automatically</li>
207 * <li>NOIDENTIFIERSSERVICE - when set, jalview won't automatically download
208 * available URL linkouts via www.jalview.org/services/identifiers</li>
211 * Deprecated settings:
214 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
215 * startup (JWS1 services only)</li>
216 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
217 * (JWS1 services only)</li>
218 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
219 * services in the desktop GUI</li>
220 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
221 * panel in web service preferences</li>
225 * @version $Revision$
230 * property giving log4j level for CASTOR loggers
232 public static final String CASTORLOGLEVEL = "logs.Castor.level";
235 * property giving log4j level for AXIS loggers
237 public static final String AXISLOGLEVEL = "logs.Axis.level";
240 * property giving log4j level for Jalview Log
242 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
247 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
248 .getProperty("user.home") + File.separatorChar
249 + ".sifts_downloads" + File.separatorChar;
251 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
253 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
256 * Identifiers.org download settings
258 private static final String ID_ORG_FILE = System.getProperty("user.home")
259 + File.separatorChar + ".identifiers.org.ids.json";
262 * Allowed values are PDB or mmCIF
264 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
267 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
271 * a date formatter using a fixed (rather than the user's) locale;
272 * this ensures that date properties can be written and re-read successfully
273 * even if the user changes their locale setting
275 private static final DateFormat date_format = SimpleDateFormat
276 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
277 SimpleDateFormat.MEDIUM, Locale.UK);
280 * Initialises the Jalview Application Log
283 public final static String JALVIEW_LOGGER_NAME = "JalviewLogger";
285 // save the proxy properties set at startup
286 public final static String[] startupProxyProperties = {
287 System.getProperty("http.proxyHost"),
288 System.getProperty("http.proxyPort"),
289 System.getProperty("https.proxyHost"),
290 System.getProperty("https.proxyPort"),
291 System.getProperty("http.proxyUser"),
292 System.getProperty("http.proxyPassword"),
293 System.getProperty("https.proxyUser"),
294 System.getProperty("https.proxyPassword"),
295 System.getProperty("http.nonProxyHosts") };
297 public final static String PROXYTYPE_NONE = "none";
299 // "false" and "true" for backward compatibility
300 public final static String PROXYTYPE_SYSTEM = "false";
302 public final static String PROXYTYPE_CUSTOM = "true";
304 // in-memory only storage of proxy password, safer to use char array
305 public static char[] proxyAuthPassword = null;
307 /** Jalview Properties */
308 public static Properties applicationProperties = new Properties()
310 // override results in properties output in alphabetical order
312 public synchronized Enumeration<Object> keys()
314 return Collections.enumeration(new TreeSet<>(super.keySet()));
318 /* build Properties (not all saved to .jalview_properties) */
319 public static Properties buildProperties = new Properties();
321 /** Default file is ~/.jalview_properties */
322 static String propertiesFile;
324 private static boolean propsAreReadOnly = Platform.isJS();
326 private final static String JS_PROPERTY_PREFIX = "jalview_";
329 * Loads properties from the given properties file. Any existing properties
332 public static void loadProperties(String propsFile)
334 propertiesFile = propsFile;
335 String releasePropertiesFile = null;
336 boolean defaultProperties = false;
337 if (propsFile == null && !propsAreReadOnly)
339 String channelPrefsFilename = ChannelProperties
340 .getProperty("preferences.filename");
341 String releasePrefsFilename = ".jalview_properties";
342 propertiesFile = System.getProperty("user.home") + File.separatorChar
343 + channelPrefsFilename;
344 releasePropertiesFile = System.getProperty("user.home")
345 + File.separatorChar + releasePrefsFilename;
346 defaultProperties = true;
350 // don't corrupt the file we've been given.
351 propsAreReadOnly = true;
354 if (propertiesFile == null)
356 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
357 applicationProperties);
366 // props file provided as URL
367 fis = new URL(propertiesFile).openStream();
369 "Loading jalview properties from : " + propertiesFile);
371 "Disabling Jalview writing to user's local properties file.");
372 propsAreReadOnly = true;
373 } catch (Exception ex)
379 String readPropertiesFile = propertiesFile;
380 // if we're using the usual properties file and the channel properties
381 // file doesn't exist, read .jalview_properties
382 // (but we'll still save to the channel properties file).
383 if (defaultProperties && (!new File(propertiesFile).exists())
384 && (new File(releasePropertiesFile).exists()))
386 readPropertiesFile = releasePropertiesFile;
388 fis = new FileInputStream(readPropertiesFile);
390 applicationProperties.clear();
391 applicationProperties.load(fis);
393 // remove any old build properties
395 deleteBuildProperties();
397 } catch (Exception ex)
399 System.out.println("Error reading properties file: " + ex);
403 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
404 if (getDefault("USE_PROXY", false))
406 String proxyServer = getDefault("PROXY_SERVER", ""),
407 proxyPort = getDefault("PROXY_PORT", "8080");
411 // PROXY TYPE settings (now three options "none", "false", "true", but using
412 // backward compatible strings)
413 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
414 // default to upgrading old settings
418 clearProxyProperties();
420 case PROXYTYPE_SYSTEM: // use system settings
421 resetProxyProperties();
423 case PROXYTYPE_CUSTOM: // use specified proxy settings
424 String httpHost = getDefault("PROXY_SERVER", "");
425 String httpPort = getDefault("PROXY_PORT", "8080");
426 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
427 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
428 String httpUser = getDefault("PROXY_AUTH_USER", null);
429 // https.proxyUser and https.proxyPassword are not able to be
430 // independently set in Preferences yet (or http.nonProxyHosts)
431 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
432 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
433 proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
436 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
438 Console.warn(message);
441 // LOAD THE AUTHORS FROM THE authors.props file
442 String authorDetails = resolveResourceURLFor("/authors.props");
446 if (authorDetails != null)
448 URL localJarFileURL = new URL(authorDetails);
449 InputStream in = localJarFileURL.openStream();
450 applicationProperties.load(in);
453 } catch (Exception ex)
455 System.out.println("Error reading author details: " + ex);
456 authorDetails = null;
458 if (authorDetails == null)
460 applicationProperties.remove("AUTHORS");
461 applicationProperties.remove("AUTHORFNAMES");
462 applicationProperties.remove("YEAR");
465 loadBuildProperties(false);
468 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
470 SiftsSettings.setSiftDownloadDirectory(Cache
471 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
473 SiftsSettings.setFailSafePIDThreshold(
474 Cache.getDefault("sifts_fail_safe_pid_threshold",
475 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
477 SiftsSettings.setCacheThresholdInDays(
478 Cache.getDefault("sifts_cache_threshold_in_days",
479 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
481 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
482 "https://www.jalview.org/services/identifiers"));
483 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
485 StructureImportSettings.setDefaultStructureFileFormat(
486 Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
487 StructureImportSettings
488 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
489 // StructureImportSettings
490 // .setDefaultPDBFileParser(Cache.getDefault(
491 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
493 String jnlpVersion = System.getProperty("jalview.version");
495 // jnlpVersion will be null if a latest version check for the channel needs
497 // Dont do this check if running in headless mode
499 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
500 && (System.getProperty("java.awt.headless") == null || System
501 .getProperty("java.awt.headless").equals("false")))
504 class VersionChecker extends Thread
510 String remoteBuildPropertiesUrl = Cache
511 .getAppbaseBuildProperties();
513 String orgtimeout = System
514 .getProperty("sun.net.client.defaultConnectTimeout");
515 if (orgtimeout == null)
518 System.out.println("# INFO: Setting default net timeout to "
519 + orgtimeout + " seconds.");
521 String remoteVersion = null;
524 System.setProperty("sun.net.client.defaultConnectTimeout",
526 java.net.URL url = new java.net.URL(remoteBuildPropertiesUrl);
528 BufferedReader in = new BufferedReader(
529 new InputStreamReader(url.openStream()));
531 Properties remoteBuildProperties = new Properties();
532 remoteBuildProperties.load(in);
533 remoteVersion = remoteBuildProperties.getProperty("VERSION");
534 } catch (Exception ex)
537 .println("Non-fatal exception when checking version at "
538 + remoteBuildPropertiesUrl + ":");
539 System.out.println(ex);
540 remoteVersion = getProperty("VERSION");
542 System.setProperty("sun.net.client.defaultConnectTimeout",
545 setProperty("LATEST_VERSION", remoteVersion);
549 VersionChecker vc = new VersionChecker();
554 if (jnlpVersion != null)
556 setProperty("LATEST_VERSION", jnlpVersion);
560 applicationProperties.remove("LATEST_VERSION");
564 // LOAD USERDEFINED COLOURS
565 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
566 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
571 * construct a resource URL for the given absolute resource pathname
573 * @param resourcePath
576 private static String resolveResourceURLFor(String resourcePath)
579 if (Platform.isJS() || !Cache.class.getProtectionDomain()
580 .getCodeSource().getLocation().toString().endsWith(".jar"))
584 url = Cache.class.getResource(resourcePath).toString();
585 } catch (Exception ex)
587 System.err.println("Failed to resolve resource " + resourcePath
588 + ": " + ex.getMessage());
593 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
594 .getLocation().toString().concat("!" + resourcePath));
599 public static void loadBuildProperties(boolean reportVersion)
601 String codeInstallation = getProperty("INSTALLATION");
602 boolean printVersion = codeInstallation == null;
605 * read build properties - from the Jalview jar for a Java distribution,
606 * or from codebase file in test or JalviewJS context
610 String buildDetails = resolveResourceURLFor("/.build_properties");
611 URL localJarFileURL = new URL(buildDetails);
612 InputStream in = localJarFileURL.openStream();
613 buildProperties.load(in);
615 if (buildProperties.getProperty("BUILD_DATE", null) != null)
617 applicationProperties.put("BUILD_DATE",
618 buildProperties.getProperty("BUILD_DATE"));
620 if (buildProperties.getProperty("INSTALLATION", null) != null)
622 applicationProperties.put("INSTALLATION",
623 buildProperties.getProperty("INSTALLATION"));
625 if (buildProperties.getProperty("VERSION", null) != null)
627 applicationProperties.put("VERSION",
628 buildProperties.getProperty("VERSION"));
630 } catch (Exception ex)
632 System.out.println("Error reading build details: " + ex);
633 applicationProperties.remove("VERSION");
635 String codeVersion = getProperty("VERSION");
636 codeInstallation = getProperty("INSTALLATION");
638 if (codeVersion == null)
640 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
641 codeVersion = "Test";
642 codeInstallation = "";
646 codeInstallation = " (" + codeInstallation + ")";
648 setProperty("VERSION", codeVersion);
649 new BuildDetails(codeVersion, null, codeInstallation);
650 if (printVersion && reportVersion)
652 System.out.println(ChannelProperties.getProperty("app_name")
653 + " Version: " + codeVersion + codeInstallation);
657 private static void deleteBuildProperties()
659 applicationProperties.remove("LATEST_VERSION");
660 applicationProperties.remove("VERSION");
661 applicationProperties.remove("AUTHORS");
662 applicationProperties.remove("AUTHORFNAMES");
663 applicationProperties.remove("YEAR");
664 applicationProperties.remove("BUILD_DATE");
665 applicationProperties.remove("INSTALLATION");
669 * Gets Jalview application property of given key. Returns null if key not
675 * @return Property value
677 public static String getProperty(String key)
679 String prop = applicationProperties.getProperty(key);
680 if (prop == null && Platform.isJS())
682 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
683 + "_" + JS_PROPERTY_PREFIX + key);
689 * These methods are used when checking if the saved preference is different
690 * to the default setting
693 public static boolean getDefault(String property, boolean def)
695 String string = getProperty(property);
698 def = Boolean.valueOf(string).booleanValue();
704 public static int getDefault(String property, int def)
706 String string = getProperty(property);
711 def = Integer.parseInt(string);
712 } catch (NumberFormatException e)
714 System.out.println("Error parsing int property '" + property
715 + "' with value '" + string + "'");
723 * Answers the value of the given property, or the supplied default value if
724 * the property is not set
726 public static String getDefault(String property, String def)
728 String value = getProperty(property);
729 return value == null ? def : value;
733 * Stores property in the file "HOME_DIR/.jalview_properties"
738 * String value of property
740 * @return previous value of property (or null)
742 public static Object setProperty(String key, String obj)
744 Object oldValue = null;
747 oldValue = applicationProperties.setProperty(key, obj);
748 if (propertiesFile != null && !propsAreReadOnly)
750 FileOutputStream out = new FileOutputStream(propertiesFile);
751 applicationProperties.store(out, "---JalviewX Properties File---");
754 } catch (Exception ex)
757 "Error setting property: " + key + " " + obj + "\n" + ex);
763 * remove the specified property from the jalview properties file
767 public static void removeProperty(String string)
769 applicationProperties.remove(string);
774 * save the properties to the jalview properties path
776 public static void saveProperties()
778 if (!propsAreReadOnly)
782 FileOutputStream out = new FileOutputStream(propertiesFile);
783 applicationProperties.store(out, "---JalviewX Properties File---");
785 } catch (Exception ex)
787 System.out.println("Error saving properties: " + ex);
793 * internal vamsas class discovery state
795 private static int vamsasJarsArePresent = -1;
798 * Searches for vamsas client classes on class path.
800 * @return true if vamsas client is present on classpath
802 public static boolean vamsasJarsPresent()
804 if (vamsasJarsArePresent == -1)
808 if (jalview.jbgui.GDesktop.class.getClassLoader()
809 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
812 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
813 vamsasJarsArePresent = 1;
814 JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
815 Console.getCachedLogLevel("logs.Vamsas.Level"));
816 JLoggerLog4j.addAppender(lvclient, Console.log,
817 JALVIEW_LOGGER_NAME);
818 // Tell the user that debug is enabled
819 lvclient.debug(ChannelProperties.getProperty("app_name")
820 + " Vamsas Client Debugging Output Follows.");
822 } catch (Exception e)
824 vamsasJarsArePresent = 0;
825 Console.debug("Vamsas Classes are not present");
828 return (vamsasJarsArePresent > 0);
832 * internal vamsas class discovery state
834 private static int groovyJarsArePresent = -1;
837 * Searches for vamsas client classes on class path.
839 * @return true if vamsas client is present on classpath
841 public static boolean groovyJarsPresent()
843 if (groovyJarsArePresent == -1)
847 if (Cache.class.getClassLoader()
848 .loadClass("groovy.lang.GroovyObject") != null)
851 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
852 groovyJarsArePresent = 1;
853 JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
854 Console.getCachedLogLevel("logs.Groovy.Level"));
855 JLoggerLog4j.addAppender(lgclient, Console.log,
856 JALVIEW_LOGGER_NAME);
857 // Tell the user that debug is enabled
858 lgclient.debug(ChannelProperties.getProperty("app_name")
859 + " Groovy Client Debugging Output Follows.");
863 groovyJarsArePresent = 0;
864 Console.debug("Groovy Classes are not present", e);
865 } catch (Exception e)
867 groovyJarsArePresent = 0;
868 Console.debug("Groovy Classes are not present");
871 return (groovyJarsArePresent > 0);
875 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
878 protected static Object tracker = null;
880 protected static Class trackerfocus = null;
882 protected static Class jgoogleanalyticstracker = null;
885 * Initialise the google tracker if it is not done already.
887 public static void initGoogleTracker()
891 if (jgoogleanalyticstracker == null)
893 // try to get the tracker class
896 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
897 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
898 trackerfocus = Cache.class.getClassLoader()
899 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
900 } catch (Exception e)
903 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
905 jgoogleanalyticstracker = null;
910 // now initialise tracker
911 Exception re = null, ex = null;
913 String vrs = "No Version Accessible";
916 // Google analytics tracking code for Library Finder
917 tracker = jgoogleanalyticstracker
918 .getConstructor(new Class[]
919 { String.class, String.class, String.class })
920 .newInstance(new Object[]
921 { ChannelProperties.getProperty("app_name") + " Desktop",
922 (vrs = Cache.getProperty("VERSION") + "_"
923 + Cache.getDefault("BUILD_DATE", "unknown")),
925 jgoogleanalyticstracker
926 .getMethod("trackAsynchronously", new Class[]
928 .invoke(tracker, new Object[]
929 { trackerfocus.getConstructor(new Class[] { String.class })
930 .newInstance(new Object[]
931 { "Application Started." }) });
932 } catch (RuntimeException e)
935 } catch (Exception e)
942 if (re != null || ex != null || err != null)
946 Console.debug("Caught runtime exception in googletracker init:",
952 "Failed to initialise GoogleTracker for Jalview Desktop with version "
959 "Whilst initing GoogleTracker for Jalview Desktop version "
966 Console.debug("Successfully initialised tracker.");
972 * get the user's default colour if available
978 public static Color getDefaultColour(String property, Color defcolour)
980 String colprop = getProperty(property);
985 Color col = ColorUtils.parseColourString(colprop);
988 Console.warn("Couldn't parse '" + colprop + "' as a colour for "
991 return (col == null) ? defcolour : col;
995 * store a colour as a Jalview user default property
1000 public static void setColourProperty(String property, Color colour)
1002 setProperty(property, jalview.util.Format.getHexString(colour));
1006 * Stores a formatted date in a jalview property, using a fixed locale.
1008 * @param propertyName
1010 * @return the formatted date string
1012 public static String setDateProperty(String propertyName, Date date)
1014 String formatted = date_format.format(date);
1015 setProperty(propertyName, formatted);
1020 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1021 * format) and returns as a Date, or null if parsing fails
1023 * @param propertyName
1027 public static Date getDateProperty(String propertyName)
1029 String val = getProperty(propertyName);
1034 return date_format.parse(val);
1035 } catch (Exception ex)
1037 System.err.println("Invalid or corrupt date in property '"
1038 + propertyName + "' : value was '" + val + "'");
1045 * get and parse a property as an integer. send any parsing problems to
1049 * @return null or Integer
1051 public static Integer getIntegerProperty(String property)
1053 String val = getProperty(property);
1054 if (val != null && (val = val.trim()).length() > 0)
1058 return Integer.valueOf(val);
1059 } catch (NumberFormatException x)
1061 System.err.println("Invalid integer in property '" + property
1062 + "' (value was '" + val + "')");
1069 * Set the specified value, or remove it if null or empty. Does not save the
1075 public static void setOrRemove(String propName, String value)
1077 if (propName == null)
1081 if (value == null || value.trim().length() < 1)
1083 Cache.applicationProperties.remove(propName);
1087 Cache.applicationProperties.setProperty(propName, value);
1092 * Loads in user colour schemes from files.
1095 * a '|'-delimited list of file paths
1097 public static void initUserColourSchemes(String files)
1099 if (files == null || files.length() == 0)
1104 // In case colours can't be loaded, we'll remove them
1105 // from the default list here.
1106 StringBuffer coloursFound = new StringBuffer();
1107 StringTokenizer st = new StringTokenizer(files, "|");
1108 while (st.hasMoreElements())
1110 String file = st.nextToken();
1113 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1116 if (coloursFound.length() > 0)
1118 coloursFound.append("|");
1120 coloursFound.append(file);
1121 ColourSchemes.getInstance().registerColourScheme(ucs);
1123 } catch (Exception ex)
1125 System.out.println("Error loading User ColourFile\n" + ex);
1128 if (!files.equals(coloursFound.toString()))
1130 if (coloursFound.toString().length() > 1)
1132 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1133 coloursFound.toString());
1137 applicationProperties
1138 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1144 * Initial logging information helper for various versions output
1148 * @param defaultValue
1150 private static void appendIfNotNull(StringBuilder sb, String prefix,
1151 String value, String suffix, String defaultValue)
1153 if (value == null && defaultValue == null)
1157 String line = prefix + (value != null ? value : defaultValue) + suffix;
1163 * @return Jalview version, build details and JVM platform version for console
1165 public static String getVersionDetailsForConsole()
1167 StringBuilder sb = new StringBuilder();
1168 sb.append(ChannelProperties.getProperty("app_name"))
1169 .append(" Version: ");
1170 sb.append(Cache.getDefault("VERSION", "TEST"));
1172 sb.append(ChannelProperties.getProperty("app_name"))
1173 .append(" Installation: ");
1174 sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1176 sb.append("Build Date: ");
1177 sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1179 sb.append("Java version: ");
1180 sb.append(System.getProperty("java.version"));
1182 sb.append(System.getProperty("os.arch"));
1184 sb.append(System.getProperty("os.name"));
1186 sb.append(System.getProperty("os.version"));
1188 appendIfNotNull(sb, "Install4j version: ",
1189 System.getProperty("sys.install4jVersion"), "\n", null);
1190 appendIfNotNull(sb, "Install4j template version: ",
1191 System.getProperty("installer_template_version"), "\n", null);
1192 appendIfNotNull(sb, "Launcher version: ",
1193 System.getProperty("launcher_version"), "\n", null);
1194 LookAndFeel laf = UIManager.getLookAndFeel();
1195 String lafName = laf == null ? "Not obtained" : laf.getName();
1196 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1197 sb.append("LookAndFeel: ");
1200 sb.append(lafClass);
1202 // Not displayed in release version ( determined by possible version number
1203 // regex 9[9.]*9[.-_a9]* )
1204 if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1205 Cache.getDefault("VERSION", "TEST")))
1207 appendIfNotNull(sb, "Getdown appdir: ",
1208 System.getProperty("getdownappdir"), "\n", null);
1209 appendIfNotNull(sb, "Getdown appbase: ",
1210 System.getProperty("getdownappbase"), "\n", null);
1211 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1214 return sb.toString();
1219 * @return build details as reported in splashscreen
1221 public static String getBuildDetailsForSplash()
1223 // consider returning more human friendly info
1224 // eg 'built from Source' or update channel
1225 return Cache.getDefault("INSTALLATION", "unknown");
1228 public static String getStackTraceString(Throwable t)
1230 StringWriter sw = new StringWriter();
1231 PrintWriter pw = new PrintWriter(sw);
1232 t.printStackTrace(pw);
1233 return sw.toString();
1236 // proxy properties methods
1237 public static void clearProxyProperties()
1239 setProxyProperties(null, null, null, null, null, null, null, null,
1243 public static void resetProxyProperties()
1245 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1246 startupProxyProperties[2], startupProxyProperties[3],
1247 startupProxyProperties[4],
1248 startupProxyProperties[5] == null ? null
1249 : startupProxyProperties[5].toCharArray(),
1250 startupProxyProperties[6],
1251 startupProxyProperties[7] == null ? null
1252 : startupProxyProperties[7].toCharArray(),
1253 startupProxyProperties[8]);
1254 StringBuilder sb = new StringBuilder();
1255 sb.append("Setting proxy properties to: http.proxyHost=")
1256 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1257 .append(startupProxyProperties[1])
1258 .append(startupProxyProperties[4] != null
1259 && !startupProxyProperties[4].isEmpty()
1260 ? " [" + startupProxyProperties[4] + "]"
1262 .append(", https.proxyHost=").append(startupProxyProperties[2])
1263 .append(", https.proxyPort=").append(startupProxyProperties[3])
1264 .append(startupProxyProperties[6] != null
1265 && !startupProxyProperties[6].isEmpty()
1266 ? " [" + startupProxyProperties[6] + "]"
1269 Console.debug(sb.toString());
1272 public static void setProxyPropertiesFromPreferences()
1274 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1277 public static void setProxyPropertiesFromPreferences(
1278 String previousProxyType)
1280 String proxyType = Cache.getDefault("USE_PROXY",
1281 Cache.PROXYTYPE_SYSTEM);
1282 if (previousProxyType != null
1283 && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1285 && proxyType.equals(previousProxyType))
1292 case Cache.PROXYTYPE_NONE:
1293 if (!previousProxyType.equals(proxyType))
1295 Console.info("Setting no proxy settings");
1296 Cache.setProxyProperties(null, null, null, null, null, null, null,
1300 case Cache.PROXYTYPE_CUSTOM:
1301 // always re-set a custom proxy -- it might have changed, particularly
1303 Console.info("Setting custom proxy settings");
1304 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1305 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1306 Cache.getDefault("PROXY_PORT", null),
1307 Cache.getDefault("PROXY_SERVER_HTTPS", null),
1308 Cache.getDefault("PROXY_PORT_HTTPS", null),
1309 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1311 proxyAuthSet ? Cache.proxyAuthPassword : null,
1312 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1314 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1316 default: // system proxy settings by default
1317 Console.info("Setting system proxy settings");
1318 Cache.resetProxyProperties();
1322 public static void setProxyProperties(String httpHost, String httpPort,
1323 String httpsHost, String httpsPort, String httpUser,
1324 char[] httpPassword, String httpsUser, char[] httpsPassword,
1325 String nonProxyHosts)
1327 setOrClearSystemProperty("http.proxyHost", httpHost);
1328 setOrClearSystemProperty("http.proxyPort", httpPort);
1329 setOrClearSystemProperty("https.proxyHost", httpsHost);
1330 setOrClearSystemProperty("https.proxyPort", httpsPort);
1331 setOrClearSystemProperty("http.proxyUser", httpUser);
1332 setOrClearSystemProperty("https.proxyUser", httpsUser);
1333 // note: passwords for http.proxyPassword and https.proxyPassword are sent
1334 // via the Authenticator, properties do not need to be set
1336 // are we using a custom proxy (password prompt might be required)?
1337 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1338 .equals(PROXYTYPE_CUSTOM);
1341 * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1342 * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1343 * is not re-called).
1344 * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1346 * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1348 * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1353 sun.net.www.protocol.http.AuthCacheValue
1354 .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1355 } catch (Throwable t)
1357 Cache.error(t.getMessage());
1358 Cache.debug(getStackTraceString(t));
1362 if (httpUser != null || httpsUser != null)
1366 char[] displayHttpPw = new char[httpPassword == null ? 0
1367 : httpPassword.length];
1368 Arrays.fill(displayHttpPw, '*');
1370 "CACHE Proxy: setting new Authenticator with httpUser='"
1371 + httpUser + "' httpPassword='" + displayHttpPw
1373 if (!Platform.isJS())
1375 * java.net.Authenticator not implemented in SwingJS yet
1381 Authenticator.setDefault(new Authenticator()
1384 protected PasswordAuthentication getPasswordAuthentication()
1386 if (getRequestorType() == RequestorType.PROXY)
1388 String protocol = getRequestingProtocol();
1389 boolean needProxyPasswordSet = false;
1390 if (customProxySet &&
1391 // we have a username but no password for the scheme being
1393 (protocol.equalsIgnoreCase("http")
1394 && (httpUser != null && httpUser.length() > 0
1395 && (httpPassword == null
1396 || httpPassword.length == 0)))
1397 || (protocol.equalsIgnoreCase("https")
1398 && (httpsUser != null
1399 && httpsUser.length() > 0
1400 && (httpsPassword == null
1401 || httpsPassword.length == 0))))
1403 // open Preferences -> Connections
1404 String message = MessageManager
1405 .getString("label.proxy_password_required");
1406 Preferences.openPreferences(
1407 Preferences.TabRef.CONNECTIONS_TAB, message);
1408 Preferences.getInstance()
1409 .proxyAuthPasswordCheckHighlight(true, true);
1415 if (protocol.equalsIgnoreCase("http")
1416 && getRequestingHost()
1417 .equalsIgnoreCase(httpHost)
1418 && getRequestingPort() == Integer
1422 "AUTHENTICATOR returning PasswordAuthentication(\""
1423 + httpUser + "\", '"
1424 + new String(displayHttpPw) + "')");
1425 return new PasswordAuthentication(httpUser,
1428 if (protocol.equalsIgnoreCase("https")
1429 && getRequestingHost()
1430 .equalsIgnoreCase(httpsHost)
1431 && getRequestingPort() == Integer
1432 .valueOf(httpsPort))
1434 char[] displayHttpsPw = new char[httpPassword.length];
1435 Arrays.fill(displayHttpsPw, '*');
1437 "AUTHENTICATOR returning PasswordAuthentication(\""
1438 + httpsUser + "\", '" + displayHttpsPw
1440 return new PasswordAuthentication(httpsUser,
1443 } catch (NumberFormatException e)
1445 Console.error("Problem with proxy port values [http:"
1446 + httpPort + ", https:" + httpsPort + "]");
1449 "AUTHENTICATOR after trying to get PasswordAuthentication");
1452 // non proxy request
1453 Console.debug("AUTHENTICATOR returning null");
1457 } // end of j2sIgnore for java.net.Authenticator
1459 // required to re-enable basic authentication (should be okay for a
1462 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1463 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1464 } catch (SecurityException e)
1466 Console.error("Could not set default Authenticator");
1467 Console.debug(getStackTraceString(e));
1472 // reset the Authenticator to protect http.proxyUser and
1473 // http.proxyPassword Just In Case
1474 /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1475 * has working credentials. No workaround for Java 11.
1477 if (!Platform.isJS())
1479 * java.net.Authenticator not implemented in SwingJS yet
1486 "AUTHENTICATOR setting default Authenticator to null");
1487 Authenticator.setDefault(null);
1491 // nonProxyHosts not currently configurable in Preferences
1493 "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1494 + nonProxyHosts + "\"");
1495 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1498 public static void setOrClearSystemProperty(String key, char[] value)
1500 setOrClearSystemProperty(key,
1501 (value == null) ? null : new String(value));
1504 public static void setOrClearSystemProperty(String key, String value)
1512 System.clearProperty(key);
1516 System.setProperty(key, value);
1521 * Getdown appbase methods
1524 private static final String releaseAppbase;
1526 private static String getdownAppbase;
1528 private static String getdownDistDir;
1532 if (!Platform.isJS())
1534 Float specversion = Float
1535 .parseFloat(System.getProperty("java.specification.version"));
1536 releaseAppbase = (specversion < 9)
1537 ? "https://www.jalview.org/getdown/release/1.8"
1538 : "https://www.jalview.org/getdown/release/11";
1542 // this value currenly made up, can be changed to URL that will be
1543 // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1544 releaseAppbase = "https://www.jalview.org/jalview-js";
1545 getdownAppbase = releaseAppbase;
1546 getdownDistDir = "/swingjs/j2s";
1550 // look for properties (passed in by getdown) otherwise default to release
1551 private static void setGetdownAppbase()
1553 if (getdownAppbase != null)
1557 String appbase = System.getProperty("getdownappbase");
1558 String distDir = System.getProperty("getdowndistdir");
1559 if (appbase == null)
1561 appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1562 distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1564 if (appbase == null)
1566 appbase = releaseAppbase;
1567 distDir = "release";
1569 if (appbase.endsWith("/"))
1571 appbase = appbase.substring(0, appbase.length() - 1);
1573 if (distDir == null)
1575 distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1577 getdownAppbase = appbase;
1578 getdownDistDir = distDir;
1581 public static String getGetdownAppbase()
1583 setGetdownAppbase();
1584 return getdownAppbase;
1587 public static String getAppbaseBuildProperties()
1589 String appbase = getGetdownAppbase();
1590 return appbase + "/" + getdownDistDir + "/build_properties";