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 org.apache.log4j.ConsoleAppender;
51 import org.apache.log4j.Level;
52 import org.apache.log4j.Logger;
53 import org.apache.log4j.SimpleLayout;
55 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
56 import jalview.datamodel.PDBEntry;
57 import jalview.gui.Preferences;
58 import jalview.gui.UserDefinedColours;
59 import jalview.schemes.ColourSchemeLoader;
60 import jalview.schemes.ColourSchemes;
61 import jalview.schemes.UserColourScheme;
62 import jalview.structure.StructureImportSettings;
63 import jalview.urls.IdOrgSettings;
64 import jalview.util.ChannelProperties;
65 import jalview.util.ColorUtils;
66 import jalview.util.MessageManager;
67 import jalview.util.Platform;
68 import jalview.ws.sifts.SiftsSettings;
71 * Stores and retrieves Jalview Application Properties Lists and fields within
72 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
73 * are alternative values for a tag. <br>
75 * Current properties include:
78 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
79 * logging level for axis (used for web services) <br>
81 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
82 * the logging level for castor (used for serialization) <br>
84 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
86 * <li>SCREEN_WIDTH</li>
87 * <li>SCREEN_HEIGHT</li>
88 * <li>SCREEN_Y=285</li>
89 * <li>SCREEN_X=371</li>
90 * <li>SHOW_FULLSCREEN boolean</li>
91 * <li>FONT_NAME java font name for alignment text display</li>
92 * <li>FONT_SIZE size of displayed alignment text</li>
93 * <li>FONT_STYLE style of font displayed (sequence labels are always
95 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
96 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
97 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
98 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
99 * <li>SHOW_IDENTITY show percentage identity annotation</li>
100 * <li>SHOW_QUALITY show alignment quality annotation</li>
101 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
102 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
103 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
104 * LABEL_AND_SEQUENCE</li>
105 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
106 * sequence annotations</li>
107 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
108 * annotation row</li>
109 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
110 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
111 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
112 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
113 * <li>VERSION the version of the jalview build</li>
114 * <li>BUILD_DATE date of this build</li>
115 * <li>LATEST_VERSION the latest jalview version advertised on the
116 * www.jalview.org</li>
117 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
119 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
120 * suffix to file</li>
121 * <li>RECENT_URL list of recently retrieved URLs</li>
122 * <li>RECENT_FILE list of recently opened files</li>
123 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
124 * <li>PROXY_SERVER the proxy</li>
125 * <li>PROXY_PORT</li>
126 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
128 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
130 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
131 * collecting usage statistics</li>
132 * <li>SHOW_OVERVIEW boolean for overview window display</li>
133 * <li>ANTI_ALIAS boolean for smooth fonts</li>
134 * <li>RIGHT_ALIGN_IDS boolean</li>
135 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
136 * <li>PAD_GAPS boolean</li>
137 * <li>ID_ITALICS boolean</li>
138 * <li>SHOW_JV_SUFFIX</li>
139 * <li>WRAP_ALIGNMENT</li>
140 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
142 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
143 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
145 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
147 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
148 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
149 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
150 * jalview.utils.GroupURLLink for more info</li>
151 * <li>DEFAULT_BROWSER for unix</li>
152 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
154 * <li>VERSION_CHECK (true) check for the latest release version from
155 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
156 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
158 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
160 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
161 * displayed as '.'</li>
162 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
163 * order of a newly displayed tree</li>
164 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
165 * sequence ID strings before attempting retrieval from any datasource</li>
166 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
168 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
169 * in the alignment.</li>
170 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
172 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
174 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
175 * logo normalised to row height rather than histogram height.</li>
176 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
177 * respond to selections made in other alignments containing the same sequences.
179 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
180 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
181 * warning dialog box is displayed.</li>
182 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
183 * when shading by annotation</li>
184 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
185 * when shading by annotation</li>
186 * <li>www.jalview.org (https://www.jalview.org) a property enabling all HTTP
187 * requests to be redirected to a mirror of https://www.jalview.org</li>
188 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
189 * alignment figure to accommodate even the longest sequence ID or annotation
191 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
192 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
193 * will override this).</li>
194 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
196 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
197 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
199 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
201 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
203 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
204 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
208 * Deprecated settings:
211 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
212 * startup (JWS1 services only)</li>
213 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
214 * (JWS1 services only)</li>
215 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
216 * services in the desktop GUI</li>
217 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
218 * panel in web service preferences</li>
222 * @version $Revision$
224 public class Cache implements ApplicationSingletonI
233 * In Java, this will be a static field instance, which will be
234 * application-specific; in JavaScript it will be an applet-specific instance
235 * tied to the applet's ThreadGroup.
239 public static Cache getInstance()
241 return (Cache) ApplicationSingletonProvider.getInstance(Cache.class);
245 * property giving log4j level for CASTOR loggers
247 public static final String CASTORLOGLEVEL = "logs.Castor.level";
250 * property giving log4j level for AXIS loggers
252 public static final String AXISLOGLEVEL = "logs.Axis.level";
255 * property giving log4j level for Jalview Log
257 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
262 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = Platform.getUserPath(".sifts_downloads/");
264 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
266 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
269 * Identifiers.org download settings
271 private static final String ID_ORG_FILE = Platform.getUserPath(".identifiers.org.ids.json");
274 * Allowed values are PDB or mmCIF
276 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
279 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
283 * a date formatter using a fixed (rather than the user's) locale;
284 * this ensures that date properties can be written and re-read successfully
285 * even if the user changes their locale setting
287 private static final DateFormat date_format = SimpleDateFormat
288 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
289 SimpleDateFormat.MEDIUM, Locale.UK);
292 * Initialises the Jalview Application Log
294 public static Logger log;
296 // save the proxy properties set at startup
297 public final static String[] startupProxyProperties = {
298 System.getProperty("http.proxyHost"),
299 System.getProperty("http.proxyPort"),
300 System.getProperty("https.proxyHost"),
301 System.getProperty("https.proxyPort"),
302 System.getProperty("http.proxyUser"),
303 System.getProperty("http.proxyPassword"),
304 System.getProperty("https.proxyUser"),
305 System.getProperty("https.proxyPassword"),
306 System.getProperty("http.nonProxyHosts") };
308 public final static String PROXYTYPE_NONE = "none";
310 // "false" and "true" for backward compatibility
311 public final static String PROXYTYPE_SYSTEM = "false";
313 public final static String PROXYTYPE_CUSTOM = "true";
315 // in-memory only storage of proxy password, safer to use char array
316 public static char[] proxyAuthPassword = null;
317 /** Jalview Properties */
318 private Properties applicationProperties = new Properties()
320 // override results in properties output in alphabetical order
322 public synchronized Enumeration<Object> keys()
324 return Collections.enumeration(new TreeSet<>(super.keySet()));
328 /* build Properties (not all saved to .jalview_properties) */
329 public static Properties buildProperties = new Properties();
330 /** Default file is ~/.jalview_properties */
331 static String propertiesFile;
333 private static boolean propsAreReadOnly = Platform.isJS();
335 private final static String JS_PROPERTY_PREFIX = "jalview_";
337 public static void initLogger()
345 // TODO: redirect stdout and stderr here in order to grab the output of
348 ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
350 ap.setName("JalviewLogger");
351 org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
353 Logger laxis = Logger.getLogger("org.apache.axis");
354 Logger lcastor = Logger.getLogger("org.exolab.castor");
355 jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
357 laxis.setLevel(Level.toLevel(
358 Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
359 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
360 Level.INFO.toString())));
361 lcastor = Logger.getLogger("org.exolab.castor.xml");
362 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
363 Level.INFO.toString())));
364 // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
365 // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
366 // Level.INFO.toString())));
367 // we shouldn't need to do this
368 org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
369 jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
370 .getDefault("logs.Jalview.level", Level.INFO.toString())));
371 // laxis.addAppender(ap);
372 // lcastor.addAppender(ap);
373 // jalview.bin.Cache.log.addAppender(ap);
374 // Tell the user that debug is enabled
375 jalview.bin.Cache.log.debug(ChannelProperties.getProperty("app_name")
376 + " Debugging Output Follows.");
377 } catch (Exception ex)
379 System.err.println("Problems initializing the log4j system\n");
380 ex.printStackTrace(System.err);
385 * Loads properties from the given properties file. Any existing properties are
388 public static void loadProperties(String propsFile)
391 getInstance().loadPropertiesImpl(propsFile);
395 private void loadPropertiesImpl(String propsFile)
398 propertiesFile = propsFile;
399 String releasePropertiesFile = null;
400 boolean defaultProperties = false;
401 if (propsFile == null && !propsAreReadOnly)
403 // TODO: @bsoares - for 2.12 testing: check test,develop,release props are located correctly
404 String channelPrefsFilename = ChannelProperties
405 .getProperty("preferences.filename");
406 String releasePrefsFilename = ".jalview_properties";
407 propertiesFile = Platform.getUserPath(channelPrefsFilename);
408 releasePropertiesFile = Platform.getUserPath(releasePrefsFilename);
409 defaultProperties = true;
413 // don't corrupt the file we've been given.
414 propsAreReadOnly = true;
417 if (propertiesFile == null)
419 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
420 applicationProperties);
429 // props file provided as URL
430 fis = new URL(propertiesFile).openStream();
432 "Loading jalview properties from : " + propertiesFile);
434 "Disabling Jalview writing to user's local properties file.");
435 propsAreReadOnly = true;
437 } catch (Exception ex)
443 String readPropertiesFile = propertiesFile;
444 // if we're using the usual properties file and the channel properties
445 // file doesn't exist, read .jalview_properties
446 // (but we'll still save to the channel properties file).
447 if (defaultProperties && (!new File(propertiesFile).exists())
448 && (new File(releasePropertiesFile).exists()))
450 readPropertiesFile = releasePropertiesFile;
452 fis = new FileInputStream(readPropertiesFile);
454 applicationProperties.clear();
455 applicationProperties.load(fis);
457 // remove any old build properties
459 deleteBuildProperties();
461 } catch (Exception ex)
463 System.out.println("Error reading properties file: " + ex);
466 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
467 if (getDefault("USE_PROXY", false))
469 String proxyServer = getDefault("PROXY_SERVER", ""),
470 proxyPort = getDefault("PROXY_PORT", "8080");
474 // PROXY TYPE settings (now three options "none", "false", "true", but using
475 // backward compatible strings)
476 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
477 // default to upgrading old settings
481 clearProxyProperties();
483 case PROXYTYPE_SYSTEM: // use system settings
484 resetProxyProperties();
486 case PROXYTYPE_CUSTOM: // use specified proxy settings
487 String httpHost = getDefault("PROXY_SERVER", "");
488 String httpPort = getDefault("PROXY_PORT", "8080");
489 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
490 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
491 String httpUser = getDefault("PROXY_AUTH_USER", null);
492 // https.proxyUser and https.proxyPassword are not able to be
493 // independently set in Preferences yet (or http.nonProxyHosts)
494 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
495 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
496 proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
499 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
504 // LOAD THE AUTHORS FROM THE authors.props file
505 String authorDetails = resolveResourceURLFor("/authors.props");
509 if (authorDetails != null)
511 URL localJarFileURL = new URL(authorDetails);
512 InputStream in = localJarFileURL.openStream();
513 applicationProperties.load(in);
516 } catch (Exception ex)
518 System.out.println("Error reading author details: " + ex);
519 authorDetails = null;
521 if (authorDetails == null)
523 applicationProperties.remove("AUTHORS");
524 applicationProperties.remove("AUTHORFNAMES");
525 applicationProperties.remove("YEAR");
528 loadBuildProperties(false);
531 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
533 SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
534 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
536 SiftsSettings.setFailSafePIDThreshold(
537 jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
538 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
540 SiftsSettings.setCacheThresholdInDays(
541 jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
542 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
544 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
545 "https://www.jalview.org/services/identifiers"));
546 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
548 StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
549 .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
550 StructureImportSettings
551 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
552 // StructureImportSettings
553 // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
554 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
556 String jnlpVersion = System.getProperty("jalview.version");
558 // jnlpVersion will be null if a latest version check for the channel needs
560 // Dont do this check if running in headless mode
562 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
563 && (System.getProperty("java.awt.headless") == null || System
564 .getProperty("java.awt.headless").equals("false")))
566 class VersionChecker extends Thread
571 String remoteBuildPropertiesUrl = Cache
572 .getAppbaseBuildProperties();
573 String orgtimeout = System
574 .getProperty("sun.net.client.defaultConnectTimeout");
575 if (orgtimeout == null)
578 System.out.println("# INFO: Setting default net timeout to "
579 + orgtimeout + " seconds.");
581 String remoteVersion = null;
584 System.setProperty("sun.net.client.defaultConnectTimeout",
586 java.net.URL url = new java.net.URL(remoteBuildPropertiesUrl);
587 BufferedReader in = new BufferedReader(
588 new InputStreamReader(url.openStream()));
590 Properties remoteBuildProperties = new Properties();
591 remoteBuildProperties.load(in);
592 remoteVersion = remoteBuildProperties.getProperty("VERSION");
593 } catch (Exception ex)
596 .println("Non-fatal exception when checking version at "
597 + remoteBuildPropertiesUrl + ":");
598 System.out.println(ex);
599 remoteVersion = getProperty("VERSION");
601 System.setProperty("sun.net.client.defaultConnectTimeout",
604 setProperty("LATEST_VERSION", remoteVersion);
608 VersionChecker vc = new VersionChecker();
613 if (jnlpVersion != null)
615 setProperty("LATEST_VERSION", jnlpVersion);
619 applicationProperties.remove("LATEST_VERSION");
623 // LOAD USERDEFINED COLOURS
624 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
625 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
630 * construct a resource URL for the given absolute resource pathname
632 * @param resourcePath
635 private static String resolveResourceURLFor(String resourcePath)
638 if (Platform.isJS() || !Cache.class.getProtectionDomain()
639 .getCodeSource().getLocation().toString().endsWith(".jar"))
643 url = Cache.class.getResource(resourcePath).toString();
644 } catch (Exception ex)
646 System.err.println("Failed to resolve resource " + resourcePath
647 + ": " + ex.getMessage());
652 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
653 .getLocation().toString().concat("!" + resourcePath));
658 public void loadBuildProperties(boolean reportVersion)
660 String codeInstallation = getProperty("INSTALLATION");
661 boolean printVersion = codeInstallation == null;
664 * read build properties - from the Jalview jar for a Java distribution,
665 * or from codebase file in test or JalviewJS context
669 String buildDetails = resolveResourceURLFor("/.build_properties");
670 URL localJarFileURL = new URL(buildDetails);
671 InputStream in = localJarFileURL.openStream();
672 buildProperties.load(in);
674 if (buildProperties.getProperty("BUILD_DATE", null) != null)
676 applicationProperties.put("BUILD_DATE",
677 buildProperties.getProperty("BUILD_DATE"));
679 if (buildProperties.getProperty("INSTALLATION", null) != null)
681 applicationProperties.put("INSTALLATION",
682 buildProperties.getProperty("INSTALLATION"));
684 if (buildProperties.getProperty("VERSION", null) != null)
686 applicationProperties.put("VERSION",
687 buildProperties.getProperty("VERSION"));
689 } catch (Exception ex)
691 System.out.println("Error reading build details: " + ex);
692 applicationProperties.remove("VERSION");
694 String codeVersion = getProperty("VERSION");
695 codeInstallation = getProperty("INSTALLATION");
697 if (codeVersion == null)
699 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
700 codeVersion = "Test";
701 codeInstallation = "";
705 codeInstallation = " (" + codeInstallation + ")";
707 setProperty("VERSION", codeVersion);
708 new BuildDetails(codeVersion, null, codeInstallation);
709 if (printVersion && reportVersion)
711 System.out.println(ChannelProperties.getProperty("app_name")
712 + " Version: " + codeVersion + codeInstallation);
716 private void deleteBuildProperties()
718 applicationProperties.remove("LATEST_VERSION");
719 applicationProperties.remove("VERSION");
720 applicationProperties.remove("AUTHORS");
721 applicationProperties.remove("AUTHORFNAMES");
722 applicationProperties.remove("YEAR");
723 applicationProperties.remove("BUILD_DATE");
724 applicationProperties.remove("INSTALLATION");
728 * Gets Jalview application property of given key. Returns null if key not found
733 * @return Property value
735 public static String getProperty(String key)
737 String prop = getInstance().applicationProperties.getProperty(key);
738 // if (prop == null && Platform.isJS())
740 // prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
741 // + "_" + JS_PROPERTY_PREFIX + key);
747 * These methods are used when checking if the saved preference is different to
748 * the default setting
751 public static boolean getDefault(String property, boolean def)
753 String string = getProperty(property);
756 def = Boolean.valueOf(string).booleanValue();
762 public static int getDefault(String property, int def)
764 String string = getProperty(property);
769 def = Integer.parseInt(string);
770 } catch (NumberFormatException e)
772 System.out.println("Error parsing int property '" + property
773 + "' with value '" + string + "'");
781 * Answers the value of the given property, or the supplied default value if the
782 * property is not set
784 public static String getDefault(String property, String def)
786 String value = getProperty(property);
787 return value == null ? def : value;
791 * Stores property in the file "HOME_DIR/.jalview_properties"
796 * String value of property
798 * @return previous value of property (or null)
800 public static Object setProperty(String key, String obj)
802 return getInstance().setPropertyImpl(key, obj, true);
806 * Removes the specified property from the jalview properties file
810 public static void removeProperty(String key)
812 getInstance().removePropertyImpl(key, true);
816 * Removes the named property for the running application, without saving the
819 * BH noting that ColourMenuHelper calls this. If the intent is to save, then
820 * simply chanet that call to removeProperty(key).
824 public static void removePropertyNoSave(String key)
829 removePropertyImpl(key, false);
833 * Removes the named property, and optionally saves the current properties to
839 private void removePropertyImpl(String key, boolean andSave)
841 applicationProperties.remove(key);
847 * save the properties to the jalview properties path
849 public static void saveProperties()
851 getInstance().savePropertiesImpl();
855 * save the properties to the jalview properties path
857 private void savePropertiesImpl()
860 if (!propsAreReadOnly)
864 FileOutputStream out = new FileOutputStream(propertiesFile);
865 applicationProperties.store(out, "---JalviewX Properties File---");
867 } catch (Exception ex)
869 System.out.println("Error saving properties: " + ex);
875 * internal vamsas class discovery state
877 private static int vamsasJarsArePresent = -1;
880 * Searches for vamsas client classes on class path.
882 * @return true if vamsas client is present on classpath
884 public static boolean vamsasJarsPresent()
886 if (vamsasJarsArePresent == -1)
890 if (jalview.jbgui.GDesktop.class.getClassLoader()
891 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
893 jalview.bin.Cache.log.debug(
894 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
895 vamsasJarsArePresent = 1;
896 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
897 lvclient.setLevel(Level.toLevel(Cache
898 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
900 lvclient.addAppender(log.getAppender("JalviewLogger"));
901 // Tell the user that debug is enabled
902 lvclient.debug(ChannelProperties.getProperty("app_name")
903 + " Vamsas Client Debugging Output Follows.");
905 } catch (Exception e)
907 vamsasJarsArePresent = 0;
908 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
911 return (vamsasJarsArePresent > 0);
915 * internal vamsas class discovery state
917 private static int groovyJarsArePresent = -1;
920 * Searches for vamsas client classes on class path.
922 * @return true if vamsas client is present on classpath
924 public static boolean groovyJarsPresent()
926 if (groovyJarsArePresent == -1)
930 if (Cache.class.getClassLoader()
931 .loadClass("groovy.lang.GroovyObject") != null)
933 jalview.bin.Cache.log.debug(
934 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
935 groovyJarsArePresent = 1;
936 Logger lgclient = Logger.getLogger("groovy");
937 lgclient.setLevel(Level.toLevel(Cache
938 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
940 lgclient.addAppender(log.getAppender("JalviewLogger"));
941 // Tell the user that debug is enabled
942 lgclient.debug(ChannelProperties.getProperty("app_name")
943 + " Groovy Client Debugging Output Follows.");
947 groovyJarsArePresent = 0;
948 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
949 } catch (Exception e)
951 groovyJarsArePresent = 0;
952 jalview.bin.Cache.log.debug("Groovy Classes are not present");
955 return (groovyJarsArePresent > 0);
959 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
962 protected static Object tracker = null;
964 protected static Class trackerfocus = null;
966 protected static Class jgoogleanalyticstracker = null;
969 * Initialise the google tracker if it is not done already.
971 public static void initGoogleTracker()
975 if (jgoogleanalyticstracker == null)
977 // try to get the tracker class
980 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
981 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
982 trackerfocus = Cache.class.getClassLoader()
983 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
984 } catch (Exception e)
987 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
989 jgoogleanalyticstracker = null;
994 // now initialise tracker
995 Exception re = null, ex = null;
997 String vrs = "No Version Accessible";
1000 // Google analytics tracking code for Library Finder
1001 tracker = jgoogleanalyticstracker
1002 .getConstructor(new Class[]
1003 { String.class, String.class, String.class })
1004 .newInstance(new Object[]
1005 { ChannelProperties.getProperty("app_name") + " Desktop",
1006 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
1007 + jalview.bin.Cache.getDefault("BUILD_DATE",
1010 jgoogleanalyticstracker
1011 .getMethod("trackAsynchronously", new Class[]
1013 .invoke(tracker, new Object[]
1014 { trackerfocus.getConstructor(new Class[] { String.class })
1015 .newInstance(new Object[]
1016 { "Application Started." }) });
1017 } catch (RuntimeException e)
1020 } catch (Exception e)
1027 if (re != null || ex != null || err != null)
1033 log.debug("Caught runtime exception in googletracker init:",
1039 "Failed to initialise GoogleTracker for Jalview Desktop with version "
1046 "Whilst initing GoogleTracker for Jalview Desktop version "
1056 "Debug: Caught runtime exception in googletracker init:"
1058 re.printStackTrace();
1063 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
1065 ex.printStackTrace();
1071 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1073 err.printStackTrace();
1079 log.debug("Successfully initialised tracker.");
1085 * get the user's default colour if available
1091 public static Color getDefaultColour(String property, Color defcolour)
1093 String colprop = getProperty(property);
1094 if (colprop == null)
1098 Color col = ColorUtils.parseColourString(colprop);
1101 log.warn("Couldn't parse '" + colprop + "' as a colour for "
1104 return (col == null) ? defcolour : col;
1108 * store a colour as a Jalview user default property
1113 public static void setColourPropertyNoSave(String property, Color colour)
1115 setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
1119 * Stores a formatted date in a jalview property, using a fixed locale.
1121 * @param propertyName
1123 * @return the formatted date string
1125 public static String setDateProperty(String propertyName, Date date)
1127 String formatted = date_format.format(date);
1128 setProperty(propertyName, formatted);
1133 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1134 * format) and returns as a Date, or null if parsing fails
1136 * @param propertyName
1140 public static Date getDateProperty(String propertyName)
1142 String val = getProperty(propertyName);
1148 if ((val = val.trim()).indexOf(",") < 0 && val.indexOf("-") >= 0 && val.indexOf(" ") == val.lastIndexOf(" ")) {
1149 val = val.replace(" ",", ").replace('-',' ');
1151 Date date = date_format.parse(val);
1153 } catch (Exception ex)
1155 System.err.println("Invalid or corrupt date in property '"
1156 + propertyName + "' : value was '" + val + "'");
1163 * get and parse a property as an integer. send any parsing problems to
1167 * @return null or Integer
1169 public static Integer getIntegerProperty(String property)
1171 String val = getProperty(property);
1172 if (val != null && (val = val.trim()).length() > 0)
1176 return Integer.valueOf(val);
1177 } catch (NumberFormatException x)
1179 System.err.println("Invalid integer in property '" + property
1180 + "' (value was '" + val + "')");
1187 * Set the specified value, or remove it if null or empty. Does not save the
1193 public static void setOrRemove(String propName, String value)
1195 if (propName == null)
1199 if (value == null || value.trim().length() < 1)
1201 getInstance().applicationProperties.remove(propName);
1205 getInstance().applicationProperties.setProperty(propName, value);
1210 * Loads in user colour schemes from files.
1213 * a '|'-delimited list of file paths
1215 public static void initUserColourSchemes(String files)
1217 if (files == null || files.length() == 0)
1222 // In case colours can't be loaded, we'll remove them
1223 // from the default list here.
1224 StringBuffer coloursFound = new StringBuffer();
1225 StringTokenizer st = new StringTokenizer(files, "|");
1226 while (st.hasMoreElements())
1228 String file = st.nextToken();
1231 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1234 if (coloursFound.length() > 0)
1236 coloursFound.append("|");
1238 coloursFound.append(file);
1239 ColourSchemes.getInstance().registerColourScheme(ucs);
1241 } catch (Exception ex)
1243 System.out.println("Error loading User ColourFile\n" + ex);
1246 if (!files.equals(coloursFound.toString()))
1248 if (coloursFound.toString().length() > 1)
1250 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1251 coloursFound.toString());
1255 getInstance().applicationProperties
1256 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1262 * Initial logging information helper for various versions output
1266 * @param defaultValue
1268 private static void appendIfNotNull(StringBuilder sb, String prefix,
1269 String value, String suffix, String defaultValue)
1271 if (value == null && defaultValue == null)
1275 String line = prefix + (value != null ? value : defaultValue) + suffix;
1281 * @return Jalview version, build details and JVM platform version for console
1283 public static String getVersionDetailsForConsole()
1285 StringBuilder sb = new StringBuilder();
1286 sb.append(ChannelProperties.getProperty("app_name"))
1287 .append(" Version: ");
1288 sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1290 sb.append(ChannelProperties.getProperty("app_name"))
1291 .append(" Installation: ");
1292 sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1294 sb.append("Build Date: "
1295 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1297 sb.append("Java version: ");
1298 sb.append(System.getProperty("java.version"));
1300 sb.append(System.getProperty("os.arch"));
1302 sb.append(System.getProperty("os.name"));
1304 sb.append(System.getProperty("os.version"));
1306 appendIfNotNull(sb, "Install4j version: ",
1307 System.getProperty("sys.install4jVersion"), "\n", null);
1308 appendIfNotNull(sb, "Install4j template version: ",
1309 System.getProperty("installer_template_version"), "\n", null);
1310 appendIfNotNull(sb, "Launcher version: ",
1311 System.getProperty("launcher_version"), "\n", null);
1312 LookAndFeel laf = UIManager.getLookAndFeel();
1313 String lafName = laf == null ? "Not obtained" : laf.getName();
1314 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1315 sb.append("LookAndFeel: ");
1318 sb.append(lafClass);
1320 // Not displayed in release version ( determined by possible version number
1321 // regex 9[9.]*9[.-_a9]* )
1322 if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1323 jalview.bin.Cache.getDefault("VERSION", "TEST")))
1325 appendIfNotNull(sb, "Getdown appdir: ",
1326 System.getProperty("getdownappdir"), "\n", null);
1327 appendIfNotNull(sb, "Getdown appbase: ",
1328 System.getProperty("getdownappbase"), "\n", null);
1329 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1332 return sb.toString();
1337 * @return build details as reported in splashscreen
1339 public static String getBuildDetailsForSplash()
1341 // consider returning more human friendly info
1342 // eg 'built from Source' or update channel
1343 return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1348 * For AppletParams and Preferences ok_actionPerformed and
1349 * startupFileTextfield_mouseClicked
1351 * Sets a property value for the running application, without saving it to the
1357 public static void setPropertyNoSave(String key, String obj)
1359 getInstance().setPropertyImpl(key, obj, false);
1363 * Sets a property value, and optionally also saves the current properties to
1371 private Object setPropertyImpl(
1372 String key, String obj, boolean andSave)
1374 Object oldValue = null;
1377 oldValue = applicationProperties.setProperty(key, obj);
1378 if (andSave && !propsAreReadOnly && propertiesFile != null)
1380 FileOutputStream out = new FileOutputStream(propertiesFile);
1381 applicationProperties.store(out, "---JalviewX Properties File---");
1384 } catch (Exception ex)
1387 "Error setting property: " + key + " " + obj + "\n" + ex);
1392 public static String getStackTraceString(Throwable t)
1394 StringWriter sw = new StringWriter();
1395 PrintWriter pw = new PrintWriter(sw);
1396 t.printStackTrace(pw);
1397 return sw.toString();
1400 // proxy properties methods
1401 public static void clearProxyProperties()
1403 setProxyProperties(null, null, null, null, null, null, null, null,
1407 public static void resetProxyProperties()
1409 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1410 startupProxyProperties[2], startupProxyProperties[3],
1411 startupProxyProperties[4],
1412 startupProxyProperties[5] == null ? null
1413 : startupProxyProperties[5].toCharArray(),
1414 startupProxyProperties[6],
1415 startupProxyProperties[7] == null ? null
1416 : startupProxyProperties[7].toCharArray(),
1417 startupProxyProperties[8]);
1418 StringBuilder sb = new StringBuilder();
1419 sb.append("Setting proxy properties to: http.proxyHost=")
1420 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1421 .append(startupProxyProperties[1])
1422 .append(startupProxyProperties[4] != null
1423 && !startupProxyProperties[4].isEmpty()
1424 ? " [" + startupProxyProperties[4] + "]"
1426 .append(", https.proxyHost=").append(startupProxyProperties[2])
1427 .append(", https.proxyPort=").append(startupProxyProperties[3])
1428 .append(startupProxyProperties[6] != null
1429 && !startupProxyProperties[6].isEmpty()
1430 ? " [" + startupProxyProperties[6] + "]"
1433 Cache.debug(sb.toString());
1436 public static void setProxyPropertiesFromPreferences()
1438 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1441 public static void setProxyPropertiesFromPreferences(
1442 String previousProxyType)
1444 String proxyType = Cache.getDefault("USE_PROXY",
1445 Cache.PROXYTYPE_SYSTEM);
1446 if (previousProxyType != null
1447 && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1449 && proxyType.equals(previousProxyType))
1456 case Cache.PROXYTYPE_NONE:
1457 if (!previousProxyType.equals(proxyType))
1459 Cache.log.info("Setting no proxy settings");
1460 Cache.setProxyProperties(null, null, null, null, null, null, null,
1464 case Cache.PROXYTYPE_CUSTOM:
1465 // always re-set a custom proxy -- it might have changed, particularly
1467 Cache.log.info("Setting custom proxy settings");
1468 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1469 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1470 Cache.getDefault("PROXY_PORT", null),
1471 Cache.getDefault("PROXY_SERVER_HTTPS", null),
1472 Cache.getDefault("PROXY_PORT_HTTPS", null),
1473 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1475 proxyAuthSet ? Cache.proxyAuthPassword : null,
1476 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1478 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1480 default: // system proxy settings by default
1481 Cache.log.info("Setting system proxy settings");
1482 Cache.resetProxyProperties();
1486 public static void setProxyProperties(String httpHost, String httpPort,
1487 String httpsHost, String httpsPort, String httpUser,
1488 char[] httpPassword, String httpsUser, char[] httpsPassword,
1489 String nonProxyHosts)
1491 setOrClearSystemProperty("http.proxyHost", httpHost);
1492 setOrClearSystemProperty("http.proxyPort", httpPort);
1493 setOrClearSystemProperty("https.proxyHost", httpsHost);
1494 setOrClearSystemProperty("https.proxyPort", httpsPort);
1495 setOrClearSystemProperty("http.proxyUser", httpUser);
1496 setOrClearSystemProperty("https.proxyUser", httpsUser);
1497 // note: passwords for http.proxyPassword and https.proxyPassword are sent
1498 // via the Authenticator, properties do not need to be set
1500 // are we using a custom proxy (password prompt might be required)?
1501 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1502 .equals(PROXYTYPE_CUSTOM);
1505 * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1506 * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1507 * is not re-called).
1508 * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1510 * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1512 * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1517 sun.net.www.protocol.http.AuthCacheValue
1518 .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1519 } catch (Throwable t)
1521 Cache.error(t.getMessage());
1522 Cache.debug(getStackTraceString(t));
1526 if (httpUser != null || httpsUser != null)
1530 char[] displayHttpPw = new char[httpPassword == null ? 0
1531 : httpPassword.length];
1532 Arrays.fill(displayHttpPw, '*');
1533 Cache.debug("CACHE Proxy: setting new Authenticator with httpUser='"
1534 + httpUser + "' httpPassword='" + displayHttpPw + "'");
1535 if (!Platform.isJS())
1537 * java.net.Authenticator not implemented in SwingJS yet
1543 Authenticator.setDefault(new Authenticator()
1546 protected PasswordAuthentication getPasswordAuthentication()
1548 if (getRequestorType() == RequestorType.PROXY)
1550 String protocol = getRequestingProtocol();
1551 boolean needProxyPasswordSet = false;
1552 if (customProxySet &&
1553 // we have a username but no password for the scheme being
1555 (protocol.equalsIgnoreCase("http")
1556 && (httpUser != null && httpUser.length() > 0
1557 && (httpPassword == null
1558 || httpPassword.length == 0)))
1559 || (protocol.equalsIgnoreCase("https")
1560 && (httpsUser != null
1561 && httpsUser.length() > 0
1562 && (httpsPassword == null
1563 || httpsPassword.length == 0))))
1565 // open Preferences -> Connections
1566 String message = MessageManager
1567 .getString("label.proxy_password_required");
1568 Preferences.openPreferences(
1569 Preferences.TabRef.CONNECTIONS_TAB, message);
1570 Preferences.getInstance()
1571 .proxyAuthPasswordCheckHighlight(true, true);
1577 if (protocol.equalsIgnoreCase("http")
1578 && getRequestingHost()
1579 .equalsIgnoreCase(httpHost)
1580 && getRequestingPort() == Integer
1584 "AUTHENTICATOR returning PasswordAuthentication(\""
1585 + httpUser + "\", '"
1586 + new String(displayHttpPw) + "')");
1587 return new PasswordAuthentication(httpUser,
1590 if (protocol.equalsIgnoreCase("https")
1591 && getRequestingHost()
1592 .equalsIgnoreCase(httpsHost)
1593 && getRequestingPort() == Integer
1594 .valueOf(httpsPort))
1596 char[] displayHttpsPw = new char[httpPassword.length];
1597 Arrays.fill(displayHttpsPw, '*');
1599 "AUTHENTICATOR returning PasswordAuthentication(\""
1600 + httpsUser + "\", '" + displayHttpsPw
1602 return new PasswordAuthentication(httpsUser,
1605 } catch (NumberFormatException e)
1607 Cache.error("Problem with proxy port values [http:"
1608 + httpPort + ", https:" + httpsPort + "]");
1611 "AUTHENTICATOR after trying to get PasswordAuthentication");
1614 // non proxy request
1615 Cache.debug("AUTHENTICATOR returning null");
1619 } // end of j2sIgnore for java.net.Authenticator
1621 // required to re-enable basic authentication (should be okay for a
1624 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1625 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1626 } catch (SecurityException e)
1628 Cache.error("Could not set default Authenticator");
1629 Cache.debug(getStackTraceString(e));
1634 // reset the Authenticator to protect http.proxyUser and
1635 // http.proxyPassword Just In Case
1636 /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1637 * has working credentials. No workaround for Java 11.
1639 if (!Platform.isJS())
1641 * java.net.Authenticator not implemented in SwingJS yet
1647 Cache.debug("AUTHENTICATOR setting default Authenticator to null");
1648 Authenticator.setDefault(null);
1652 // nonProxyHosts not currently configurable in Preferences
1653 Cache.debug("AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1654 + nonProxyHosts + "\"");
1655 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1658 public static void setOrClearSystemProperty(String key, char[] value)
1660 setOrClearSystemProperty(key,
1661 (value == null) ? null : new String(value));
1664 public static void setOrClearSystemProperty(String key, String value)
1672 System.clearProperty(key);
1676 System.setProperty(key, value);
1680 public final static int TRACE = 10;
1682 public final static int DEBUG = 20;
1684 public final static int INFO = 30;
1686 public final static int WARN = 40;
1688 public final static int ERROR = 50;
1690 public static boolean println(int level, String message)
1692 if (Cache.log == null)
1695 System.err.println(message);
1696 else if (level >= INFO)
1697 System.out.println(message);
1698 // not printing debug or trace messages
1703 Cache.log.error(message);
1705 else if (level >= WARN)
1707 Cache.log.warn(message);
1709 else if (level >= INFO)
1711 Cache.log.info(message);
1713 else if (level >= DEBUG)
1715 Cache.log.debug(message);
1719 Cache.log.trace(message);
1724 public static void trace(String message)
1726 println(TRACE, message);
1729 public static void debug(String message)
1731 println(DEBUG, message);
1734 public static void info(String message)
1736 println(INFO, message);
1739 public static void warn(String message)
1741 println(WARN, message);
1744 public static void error(String message)
1746 println(ERROR, message);
1750 * Getdown appbase methods
1753 private static final String releaseAppbase;
1755 private static String getdownAppbase;
1757 private static String getdownDistDir;
1761 if (!Platform.isJS())
1763 Float specversion = Float
1764 .parseFloat(System.getProperty("java.specification.version"));
1765 releaseAppbase = (specversion < 9)
1766 ? "https://www.jalview.org/getdown/release/1.8"
1767 : "https://www.jalview.org/getdown/release/11";
1771 // this value currenly made up, can be changed to URL that will be
1772 // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1773 releaseAppbase = "https://www.jalview.org/jalview-js";
1774 getdownAppbase = releaseAppbase;
1775 getdownDistDir = "/swingjs/j2s";
1779 // look for properties (passed in by getdown) otherwise default to release
1780 private static void setGetdownAppbase()
1782 if (getdownAppbase != null)
1786 String appbase = System.getProperty("getdownappbase");
1787 String distDir = System.getProperty("getdowndistdir");
1788 if (appbase == null)
1790 appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1791 distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1793 if (appbase == null)
1795 appbase = releaseAppbase;
1796 distDir = "release";
1798 if (appbase.endsWith("/"))
1800 appbase = appbase.substring(0, appbase.length() - 1);
1802 if (distDir == null)
1804 distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1806 getdownAppbase = appbase;
1807 getdownDistDir = distDir;
1810 public static String getGetdownAppbase()
1812 setGetdownAppbase();
1813 return getdownAppbase;
1816 public static String getAppbaseBuildProperties()
1818 String appbase = getGetdownAppbase();
1819 return appbase + "/" + getdownDistDir + "/build_properties";