Clover icon

Coverage Report

  1. Project Clover database Thu Dec 4 2025 14:43:25 GMT
  2. Package jalview.bin

File Cache.java

 

Coverage histogram

../../img/srcFileCovDistChart6.png
37% of files have more coverage

Code metrics

210
498
57
2
1,895
1,234
231
0.46
8.74
28.5
4.05

Classes

Class Line # Actions
Cache 245 478 226
0.59891659.9%
Cache.VersionChecker 583 20 5
0.740740774.1%
 

Contributing tests

This file is covered by 528 tests. .

Source view

1    /*
2    * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3    * Copyright (C) $$Year-Rel$$ The Jalview Authors
4    *
5    * This file is part of Jalview.
6    *
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.
11    *
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.
16    *
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.
20    */
21    package jalview.bin;
22   
23    import java.awt.Color;
24    import java.io.BufferedReader;
25    import java.io.File;
26    import java.io.FileInputStream;
27    import java.io.FileNotFoundException;
28    import java.io.FileOutputStream;
29    import java.io.IOException;
30    import java.io.InputStream;
31    import java.io.InputStreamReader;
32    import java.io.PrintWriter;
33    import java.io.StringWriter;
34    import java.net.Authenticator;
35    import java.net.PasswordAuthentication;
36    import java.net.URL;
37    import java.text.DateFormat;
38    import java.text.SimpleDateFormat;
39    import java.util.ArrayList;
40    import java.util.Arrays;
41    import java.util.Collection;
42    import java.util.Collections;
43    import java.util.Date;
44    import java.util.Enumeration;
45    import java.util.HashMap;
46    import java.util.List;
47    import java.util.Locale;
48    import java.util.Map;
49    import java.util.Properties;
50    import java.util.StringTokenizer;
51    import java.util.TreeSet;
52   
53    import javax.swing.LookAndFeel;
54    import javax.swing.UIManager;
55   
56    import jalview.analytics.Plausible;
57    import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
58    import jalview.bin.argparser.Arg;
59    import jalview.bin.argparser.ArgParser;
60    import jalview.datamodel.PDBEntry;
61    import jalview.gui.Preferences;
62    import jalview.gui.UserDefinedColours;
63    import jalview.log.JLoggerLog4j;
64    import jalview.schemes.ColourSchemeLoader;
65    import jalview.schemes.ColourSchemes;
66    import jalview.schemes.UserColourScheme;
67    import jalview.structure.StructureImportSettings;
68    import jalview.urls.IdOrgSettings;
69    import jalview.util.ChannelProperties;
70    import jalview.util.ColorUtils;
71    import jalview.util.HttpUtils;
72    import jalview.util.LaunchUtils;
73    import jalview.util.MessageManager;
74    import jalview.util.Platform;
75    import jalview.ws.sifts.SiftsSettings;
76   
77    /**
78    * Stores and retrieves Jalview Application Properties Lists and fields within
79    * list entries are separated by '|' symbols unless otherwise stated (|) clauses
80    * are alternative values for a tag. <br>
81    * <br>
82    * Current properties include:
83    * <ul>
84    * <br>
85    * logs.Axis.Level - one of the stringified Levels for log4j controlling the
86    * logging level for axis (used for web services) <br>
87    * </li>
88    * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
89    * the logging level for castor (used for serialization) <br>
90    * </li>
91    * <li>logs.Jalview.Level - Cache.log stringified level. <br>
92    * </li>
93    * <li>SCREEN_WIDTH</li>
94    * <li>SCREEN_HEIGHT</li>
95    * <li>SCREEN_Y=285</li>
96    * <li>SCREEN_X=371</li>
97    * <li>SHOW_FULLSCREEN boolean</li>
98    * <li>FONT_NAME java font name for alignment text display</li>
99    * <li>FONT_SIZE size of displayed alignment text</li>
100    * <li>FONT_STYLE style of font displayed (sequence labels are always
101    * italic)</li>
102    * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
103    * <li>LAST_DIRECTORY last directory for browsing alignment</li>
104    * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
105    * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
106    * <li>SHOW_IDENTITY show percentage identity annotation</li>
107    * <li>SHOW_QUALITY show alignment quality annotation</li>
108    * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
109    * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
110    * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
111    * LABEL_AND_SEQUENCE</li>
112    * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
113    * sequence annotations</li>
114    * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
115    * annotation row</li>
116    * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
117    * <li>DEFAULT_FILE_FORMAT file format used to save</li>
118    * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
119    * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
120    * <li>VERSION the version of the jalview build</li>
121    * <li>BUILD_DATE date of this build</li>
122    * <li>LATEST_VERSION the latest jalview version advertised on the
123    * www.jalview.org</li>
124    * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
125    * descriptions</li>
126    * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
127    * suffix to file</li>
128    * <li>RECENT_URL list of recently retrieved URLs</li>
129    * <li>RECENT_FILE list of recently opened files</li>
130    * <li>USE_PROXY flag for whether a http proxy is to be used</li>
131    * <li>PROXY_SERVER the proxy</li>
132    * <li>PROXY_PORT</li>
133    * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
134    * service</li>
135    * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
136    * service</li>
137    * <li>USAGESTATS (false - user prompted) Enable analytics tracker for
138    * collecting usage statistics</li>
139    * <li>SHOW_OVERVIEW boolean for overview window display</li>
140    * <li>ANTI_ALIAS boolean for smooth fonts</li>
141    * <li>RIGHT_ALIGN_IDS boolean</li>
142    * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
143    * <li>PAD_GAPS boolean</li>
144    * <li>ID_ITALICS boolean</li>
145    * <li>SHOW_JV_SUFFIX</li>
146    * <li>WRAP_ALIGNMENT</li>
147    * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
148    * style check</li>
149    * <li>BITMAP_SCALE - scale factor for PNG export - default 0.0 - native
150    * resolution</li>
151    * <li>BITMAP_HEIGHT - height bound for PNG export or 0 for unbound</li>
152    * <li>BITMAP_WIDTH - width bound for PNG export or 0 for unbound</li>
153    * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
154    * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
155    * $SEQUENCE_ID$</li>
156    * <li>STORED_LINKS list of name|url pairs which user has entered but are not
157    * currently used
158    * <li>DEFAULT_LINK name of single url to be used when user double clicks a
159    * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
160    * <li>GROUP_LINKS list of name|URL[|&lt;separator&gt;] tuples - see
161    * jalview.utils.GroupURLLink for more info</li>
162    * <li>DEFAULT_BROWSER for unix</li>
163    * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
164    * (false)</li>
165    * <li>VERSION_CHECK (true) check for the latest release version from
166    * www.jalview.org (or the alias given by the www.jalview.org property)</li>
167    * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
168    * ID tooltip</li>
169    * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
170    * ID tooltip</li>
171    * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
172    * displayed as '.'</li>
173    * <li>SORT_BY_TREE (false) sort the current alignment view according to the
174    * order of a newly displayed tree</li>
175    * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
176    * sequence ID strings before attempting retrieval from any datasource</li>
177    * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
178    * alignment.</li>
179    * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
180    * in the alignment.</li>
181    * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
182    * histogram.</li>
183    * <li>SHOW_SSCONSENSUS_HISTOGRAM (false) Show secondary structure consensus
184    * annotation row's histogram.</li>
185    * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
186    * logo.</li>
187    * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
188    * logo normalised to row height rather than histogram height.</li>
189    * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
190    * respond to selections made in other alignments containing the same sequences.
191    * </li>
192    * <li>SHOW_JWS2_SERVICES (true) when set to false, jalview will not
193    * auto-discover JABAWS services</li>
194    * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
195    * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
196    * warning dialog box is displayed.</li>
197    * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
198    * when shading by annotation</li>
199    * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
200    * when shading by annotation</li>
201    * <li>www.jalview.org (https://www.jalview.org) a property enabling all HTTP
202    * requests to be redirected to a mirror of https://www.jalview.org</li>
203    * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
204    * alignment figure to accommodate even the longest sequence ID or annotation
205    * label.</li>
206    * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
207    * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
208    * will override this).</li>
209    * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
210    * record</li>
211    * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
212    * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
213    * display</li>
214    * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
215    * display</li>
216    * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
217    * display</li>
218    * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
219    * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
220    * </li>
221    * <li>NONEWS - when set disables Jalview News from automatically appearing</li>
222    * <li>NOHTMLTEMPLATES - when set, the
223    * https://github.com/jalview/exporter-templates/tree/master/biojs repository is
224    * not downloaded automatically</li>
225    * <li>NOIDENTIFIERSSERVICE - when set, jalview won't automatically download
226    * available URL linkouts via www.jalview.org/services/identifiers</li>
227    * <li>
228    * </ul>
229    * Deprecated settings:
230    * <ul>
231    * *
232    * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
233    * startup (JWS1 services only)</li>
234    * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
235    * (JWS1 services only)</li>
236    * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
237    * services in the desktop GUI</li>
238    * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
239    * panel in web service preferences</li>
240    * </ul>
241    *
242    * @author $author$
243    * @version $Revision$
244    */
 
245    public class Cache implements ApplicationSingletonI
246    {
 
247  55 toggle private Cache()
248    {
249    // private singleton
250    }
251   
252    /**
253    * In Java, this will be a static field instance, which will be
254    * application-specific; in JavaScript it will be an applet-specific instance
255    * tied to the applet's ThreadGroup.
256    *
257    * @return
258    */
 
259  1639206 toggle public static Cache getInstance()
260    {
261  1639216 return ApplicationSingletonProvider.getInstance(Cache.class);
262    }
263   
264    /**
265    * property giving log4j level for CASTOR loggers
266    */
267    public static final String CASTORLOGLEVEL = "logs.Castor.level";
268   
269    /**
270    * property giving log4j level for AXIS loggers
271    */
272    public static final String AXISLOGLEVEL = "logs.Axis.level";
273   
274    /**
275    * property giving log4j level for Jalview Log
276    */
277    public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
278   
279    // for tests
280    public static final String BOOTSTRAP_TEST = "BOOTSTRAP_TEST";
281   
282    /**
283    * Sifts settings
284    */
285    public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = Platform
286    .getUserPath(".sifts_downloads/");
287   
288    private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
289   
290    private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
291   
292    /**
293    * Identifiers.org download settings
294    */
295    private static final String ID_ORG_FILE = Platform
296    .getUserPath(".identifiers.org.ids.json");
297   
298    /**
299    * Allowed values are PDB or mmCIF
300    */
301    private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
302    .toString();
303   
304    private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
305    .toString();
306   
307    /*
308    * a date formatter using a fixed (rather than the user's) locale;
309    * this ensures that date properties can be written and re-read successfully
310    * even if the user changes their locale setting
311    */
312    private static final DateFormat date_format = SimpleDateFormat
313    .getDateTimeInstance(SimpleDateFormat.MEDIUM,
314    SimpleDateFormat.MEDIUM, Locale.UK);
315   
316    /**
317    * Initialises the Jalview Application Log
318    */
319    public final static String JALVIEW_LOGGER_NAME = "JalviewLogger";
320   
321    // save the proxy properties set at startup
322    public final static String[] startupProxyProperties = {
323    System.getProperty("http.proxyHost"),
324    System.getProperty("http.proxyPort"),
325    System.getProperty("https.proxyHost"),
326    System.getProperty("https.proxyPort"),
327    System.getProperty("http.proxyUser"),
328    System.getProperty("http.proxyPassword"),
329    System.getProperty("https.proxyUser"),
330    System.getProperty("https.proxyPassword"),
331    System.getProperty("http.nonProxyHosts") };
332   
333    public final static String PROXYTYPE_NONE = "none";
334   
335    // "false" and "true" for backward compatibility
336    public final static String PROXYTYPE_SYSTEM = "false";
337   
338    public final static String PROXYTYPE_CUSTOM = "true";
339   
340    // in-memory only storage of proxy password, safer to use char array
341    public static char[] proxyAuthPassword = null;
342   
343    /**
344    * Session properties, set by command line, try not to affect stored
345    * properties!
346    */
347    private Map<String, String> sessionProperties = new HashMap<>();
348   
349    private boolean bypassSessionProperties = false;
350   
 
351  55 toggle public static void enableSessionProperties()
352    {
353  55 getInstance().bypassSessionProperties = false;
354    }
355   
 
356  55 toggle public static void disableSessionProperties()
357    {
358  55 getInstance().bypassSessionProperties = true;
359    }
360   
361    /** Jalview Properties */
362    private Properties applicationProperties = new Properties()
363    {
364    // override results in properties output in alphabetical order
 
365  0 toggle @Override
366    public synchronized Enumeration<Object> keys()
367    {
368  0 return Collections.enumeration(new TreeSet<>(super.keySet()));
369    }
370    };
371   
372    /* build Properties (not all saved to .jalview_properties) */
373    public static Properties buildProperties = new Properties();
374   
375    /** Default file is ~/.jalview_properties */
376    static String propertiesFile;
377   
378    private static final String fallbackPropertiesFile = ".jalview_properties";
379   
380    private static boolean propsAreReadOnly = Platform.isJS();
381   
 
382  0 toggle public static boolean isPropsAreReadOnly()
383    {
384  0 return propsAreReadOnly;
385    }
386   
 
387  25 toggle public static void setPropsAreReadOnly(boolean propsAreReadOnly)
388    {
389  25 Cache.propsAreReadOnly = propsAreReadOnly;
390    }
391   
392    private final static String JS_PROPERTY_PREFIX = "jalview_";
393   
394    /**
395    * Loads properties from the given properties file. Any existing properties
396    * are first cleared.
397    */
 
398  320 toggle public static void loadProperties(String propsFile)
399    {
400  320 getInstance().loadPropertiesImpl(propsFile);
401   
402    }
403   
 
404  320 toggle private void loadPropertiesImpl(String propsFile)
405    {
406  320 propertiesFile = propsFile;
407  320 String releasePropertiesFile = null;
408  320 boolean defaultProperties = false;
409  320 if (propsFile == null && !propsAreReadOnly)
410    {
411    // TODO: JAL-4107 @bsoares - for 2.12 testing: check test,develop,release
412    // props are located correctly
413  42 String channelPrefsFilename = ChannelProperties
414    .getProperty("preferences.filename");
415  42 String releasePrefsFilename = fallbackPropertiesFile;
416  42 propertiesFile = Platform.getUserPath(channelPrefsFilename);
417  42 releasePropertiesFile = Platform.getUserPath(releasePrefsFilename);
418  42 defaultProperties = true;
419    }
420    else
421    {
422    // don't corrupt the file we've been given.
423  278 propsAreReadOnly = true;
424    }
425   
426  320 if (propertiesFile == null)
427    { // BH 2019
428  49 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
429    applicationProperties);
430    }
431    else
432    {
433  271 try
434    {
435  271 InputStream fis;
436  271 try
437    {
438    // props file provided as URL
439  271 fis = HttpUtils.openStream(new URL(propertiesFile));
440  0 if (!Jalview.quiet())
441    {
442  0 jalview.bin.Console.outPrintln(
443    "Loading jalview properties from : " + propertiesFile);
444  0 jalview.bin.Console.outPrintln(
445    "Disabling Jalview writing to user's local properties file.");
446    }
447  0 propsAreReadOnly = true;
448    } catch (Exception ex)
449    {
450  271 fis = null;
451    }
452  271 if (fis == null)
453    {
454  271 String readPropertiesFile = propertiesFile;
455    // if we're using the usual properties file and the channel properties
456    // file doesn't exist, read .jalview_properties
457    // (but we'll still save to the channel properties file).
458  271 if (defaultProperties && (!new File(propertiesFile).exists())
459    && (new File(releasePropertiesFile).exists()))
460    {
461  0 readPropertiesFile = releasePropertiesFile;
462    }
463  271 fis = new FileInputStream(readPropertiesFile);
464    }
465  270 applicationProperties.clear();
466  270 applicationProperties.load(fis);
467   
468    // remove any old build properties
469   
470  270 deleteBuildProperties();
471  270 fis.close();
472    } catch (Exception ex)
473    {
474  1 if (!Jalview.quiet())
475  1 jalview.bin.Console
476    .outPrintln("Error reading properties file: " + ex);
477    }
478    }
479   
480    /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
481    if (getDefault("USE_PROXY", false))
482    {
483    String proxyServer = getDefault("PROXY_SERVER", ""),
484    proxyPort = getDefault("PROXY_PORT", "8080");
485    }
486    */
487   
488    // PROXY TYPE settings (now three options "none", "false", "true", but using
489    // backward compatible strings)
490  320 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
491    // default to upgrading old settings
492  320 switch (proxyType)
493    {
494  0 case PROXYTYPE_NONE:
495  0 clearProxyProperties();
496  0 break;
497  320 case PROXYTYPE_SYSTEM: // use system settings
498  320 resetProxyProperties();
499  320 break;
500  0 case PROXYTYPE_CUSTOM: // use specified proxy settings
501  0 String httpHost = getDefault("PROXY_SERVER", "");
502  0 String httpPort = getDefault("PROXY_PORT", "8080");
503  0 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
504  0 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
505  0 String httpUser = getDefault("PROXY_AUTH_USER", null);
506    // https.proxyUser and https.proxyPassword are not able to be
507    // independently set in Preferences yet (or http.nonProxyHosts)
508  0 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
509  0 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
510    proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
511  0 break;
512  0 default:
513  0 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
514    + proxyType;
515  0 Console.warn(message);
516    }
517   
518    // LOAD THE AUTHORS FROM THE authors.props file
519  320 String authorDetails = resolveResourceURLFor("/authors.props");
520   
521  320 try
522    {
523  320 if (authorDetails != null)
524    {
525  320 URL localJarFileURL = new URL(authorDetails);
526  320 InputStream in = localJarFileURL.openStream();
527  320 applicationProperties.load(in);
528  320 in.close();
529    }
530    } catch (Exception ex)
531    {
532  0 if (!Jalview.quiet())
533  0 jalview.bin.Console
534    .outPrintln("Error reading author details: " + ex);
535  0 authorDetails = null;
536    }
537  320 if (authorDetails == null)
538    {
539  0 applicationProperties.remove("AUTHORS");
540  0 applicationProperties.remove("AUTHORFNAMES");
541  0 applicationProperties.remove("YEAR");
542    }
543   
544  320 loadBuildProperties(false);
545   
546  320 SiftsSettings
547    .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
548   
549  320 SiftsSettings.setSiftDownloadDirectory(Cache
550    .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
551   
552  320 SiftsSettings.setFailSafePIDThreshold(
553    Cache.getDefault("sifts_fail_safe_pid_threshold",
554    DEFAULT_FAIL_SAFE_PID_THRESHOLD));
555   
556  320 SiftsSettings.setCacheThresholdInDays(
557    Cache.getDefault("sifts_cache_threshold_in_days",
558    DEFAULT_CACHE_THRESHOLD_IN_DAYS));
559   
560  320 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
561    "https://www.jalview.org/services/identifiers"));
562  320 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
563   
564  320 StructureImportSettings.setDefaultStructureFileFormat(
565    Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
566  320 StructureImportSettings
567    .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
568    // StructureImportSettings
569    // .setDefaultPDBFileParser(Cache.getDefault(
570    // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
571   
572  320 String jnlpVersion = System.getProperty("jalview.version");
573   
574    // jnlpVersion will be null if a latest version check for the channel needs
575    // to be done
576    // Dont do this check if running in headless mode
577   
578  320 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
579    && (System.getProperty("java.awt.headless") == null || System
580    .getProperty("java.awt.headless").equals("false")))
581    {
582   
 
583    class VersionChecker extends Thread
584    {
585   
 
586  131 toggle @Override
587    public void run()
588    {
589  131 String remoteBuildPropertiesUrl = Cache
590    .getAppbaseBuildProperties();
591   
592  130 String orgtimeout = System
593    .getProperty("sun.net.client.defaultConnectTimeout");
594  130 if (orgtimeout == null)
595    {
596  17 orgtimeout = "30";
597  17 Console.debug("Setting default net timeout to " + orgtimeout
598    + " seconds.");
599    }
600  130 String remoteVersion = null;
601  130 if (remoteBuildPropertiesUrl.startsWith("http"))
602    {
603  130 try
604    {
605  130 System.setProperty("sun.net.client.defaultConnectTimeout",
606    "5000");
607   
608  130 URL url = new URL(remoteBuildPropertiesUrl);
609   
610  130 BufferedReader in = new BufferedReader(
611    new InputStreamReader(HttpUtils.openStream(url)));
612   
613  130 Properties remoteBuildProperties = new Properties();
614  130 remoteBuildProperties.load(in);
615  130 remoteVersion = remoteBuildProperties.getProperty("VERSION");
616    } catch (Exception ex)
617    {
618  0 if (!Jalview.quiet())
619    {
620  0 jalview.bin.Console.errPrintln(
621    "Non-fatal exception when checking version at "
622    + remoteBuildPropertiesUrl + ":");
623  0 jalview.bin.Console.printStackTrace(ex);
624    }
625  0 remoteVersion = getProperty("VERSION");
626    }
627    }
628  130 System.setProperty("sun.net.client.defaultConnectTimeout",
629    orgtimeout);
630   
631  130 setProperty("LATEST_VERSION", remoteVersion);
632    }
633    }
634   
635  131 VersionChecker vc = new VersionChecker();
636  131 vc.start();
637    }
638    else
639    {
640  189 if (jnlpVersion != null)
641    {
642  0 setProperty("LATEST_VERSION", jnlpVersion);
643    }
644    else
645    {
646  189 applicationProperties.remove("LATEST_VERSION");
647    }
648    }
649   
650    // LOAD USERDEFINED COLOURS
651  320 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
652  320 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
653    false);
654    }
655   
656    /**
657    * construct a resource URL for the given absolute resource pathname
658    *
659    * @param resourcePath
660    * @return
661    */
 
662  778 toggle private static String resolveResourceURLFor(String resourcePath)
663    {
664  778 String url = null;
665  778 if (Platform.isJS() || !Cache.class.getProtectionDomain()
666    .getCodeSource().getLocation().toString().endsWith(".jar"))
667    {
668  778 try
669    {
670  778 url = Cache.class.getResource(resourcePath).toString();
671    } catch (Exception ex)
672    {
673  0 jalview.bin.Console.errPrintln("Failed to resolve resource "
674    + resourcePath + ": " + ex.getMessage());
675    }
676    }
677    else
678    {
679  0 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
680    .getLocation().toString().concat("!" + resourcePath));
681    }
682  778 return url;
683    }
684   
 
685  458 toggle public void loadBuildProperties(boolean reportVersion)
686    {
687  458 String codeInstallation = getProperty("INSTALLATION");
688  458 boolean printVersion = codeInstallation == null;
689   
690    /*
691    * read build properties - from the Jalview jar for a Java distribution,
692    * or from codebase file in test or JalviewJS context
693    */
694  458 try
695    {
696  458 String buildDetails = resolveResourceURLFor("/.build_properties");
697  458 URL localJarFileURL = new URL(buildDetails);
698  458 InputStream in = localJarFileURL.openStream();
699  458 buildProperties.load(in);
700  458 in.close();
701  458 if (buildProperties.getProperty("BUILD_DATE", null) != null)
702    {
703  458 applicationProperties.put("BUILD_DATE",
704    buildProperties.getProperty("BUILD_DATE"));
705    }
706  458 if (buildProperties.getProperty("INSTALLATION", null) != null)
707    {
708  458 applicationProperties.put("INSTALLATION",
709    buildProperties.getProperty("INSTALLATION"));
710    }
711  458 if (buildProperties.getProperty("VERSION", null) != null)
712    {
713  458 applicationProperties.put("VERSION",
714    buildProperties.getProperty("VERSION"));
715    }
716  458 if (buildProperties.getProperty("JAVA_COMPILE_VERSION", null) != null)
717    {
718  458 applicationProperties.put("JAVA_COMPILE_VERSION",
719    buildProperties.getProperty("JAVA_COMPILE_VERSION"));
720    }
721    } catch (Exception ex)
722    {
723  0 if (!Jalview.quiet())
724  0 jalview.bin.Console
725    .outPrintln("Error reading build details: " + ex);
726  0 applicationProperties.remove("VERSION");
727    }
728  458 String codeVersion = getProperty("VERSION");
729  458 codeInstallation = getProperty("INSTALLATION");
730   
731  458 if (codeVersion == null)
732    {
733    // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
734  0 codeVersion = "Test";
735  0 codeInstallation = "";
736    }
737    else
738    {
739  458 codeInstallation = " (" + codeInstallation + ")";
740    }
741  458 setProperty("VERSION", codeVersion);
742  458 new BuildDetails(codeVersion, null, codeInstallation);
743  458 if (printVersion && reportVersion)
744    {
745  51 jalview.bin.Console
746    .outPrintln(ChannelProperties.getProperty("app_name")
747    + " version: " + codeVersion + codeInstallation);
748    }
749    }
750   
 
751  270 toggle private void deleteBuildProperties()
752    {
753  270 applicationProperties.remove("LATEST_VERSION");
754  270 applicationProperties.remove("VERSION");
755  270 applicationProperties.remove("AUTHORS");
756  270 applicationProperties.remove("AUTHORFNAMES");
757  270 applicationProperties.remove("YEAR");
758  270 applicationProperties.remove("BUILD_DATE");
759  270 applicationProperties.remove("INSTALLATION");
760    }
761   
762    /**
763    * Gets Jalview application property of given key. Returns null if key not
764    * found
765    *
766    * @param key
767    * Name of property
768    *
769    * @return Property value
770    */
 
771  545652 toggle public static String getProperty(String key)
772    {
773  545653 return getProperty(key, false);
774    }
775   
 
776  545652 toggle public static String getProperty(String key,
777    boolean skipSessionProperties)
778    {
779  545652 String prop = null;
780  545651 if (!(skipSessionProperties || getInstance().bypassSessionProperties))
781    {
782  544737 prop = getSessionProperty(key);
783    }
784  545648 if (prop == null)
785    {
786  545648 prop = getInstance().applicationProperties.getProperty(key);
787    }
788    // TODO JAL-4107 - test JalviewJS picks up js properties correctly
789    // if (prop == null && Platform.isJS())
790    // {
791    // prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
792    // + "_" + JS_PROPERTY_PREFIX + key);
793    // }
794  545652 return prop;
795    }
796   
797    /**
798    * These methods are used when checking if the saved preference is different
799    * to the default setting
800    */
801   
 
802  530560 toggle public static boolean getDefault(String property, boolean def)
803    {
804  530561 String string = getProperty(property);
805  530561 if (string != null)
806    {
807  415445 def = Boolean.valueOf(string).booleanValue();
808    }
809   
810  530561 return def;
811    }
812   
 
813  286 toggle public static int getDefault(String property, int def)
814    {
815  286 String string = getProperty(property);
816  286 if (string != null)
817    {
818  14 try
819    {
820  14 def = Integer.parseInt(string);
821    } catch (NumberFormatException e)
822    {
823  0 if (!Jalview.quiet())
824  0 jalview.bin.Console.errPrintln("Error parsing int property '"
825    + property + "' with value '" + string + "'");
826    }
827    }
828   
829  286 return def;
830    }
831   
 
832  24 toggle public static float getDefault(String property, float def)
833    {
834  24 String string = getProperty(property);
835  24 if (string != null)
836    {
837  4 try
838    {
839  4 def = Float.parseFloat(string);
840    } catch (NumberFormatException e)
841    {
842  0 if (!Jalview.quiet())
843  0 jalview.bin.Console.errPrintln("Error parsing float property '"
844    + property + "' with value '" + string + "'");
845    }
846    }
847   
848  24 return def;
849    }
850   
851    /**
852    * Answers the value of the given property, or the supplied default value if
853    * the property is not set
854    */
 
855  10200 toggle public static String getDefault(String property, String def)
856    {
857  10200 String value = getProperty(property);
858  10200 return value == null ? def : value;
859    }
860   
861    /**
862    * Stores property in the file "HOME_DIR/.jalview_properties"
863    *
864    * @param key
865    * Name of object
866    * @param obj
867    * String value of property
868    *
869    * @return previous value of property (or null)
870    */
 
871  2359 toggle public static Object setProperty(String key, String obj)
872    {
873  2359 return getInstance().setPropertyImpl(key, obj, true);
874    }
875   
876    /**
877    * Removes the specified property from the jalview properties file
878    *
879    * @param key
880    */
 
881  30 toggle public static void removeProperty(String key)
882    {
883  30 getInstance().removePropertyImpl(key, true);
884    }
885   
886    /**
887    * Removes the named property for the running application, without saving the
888    * properties file
889    *
890    * BH noting that ColourMenuHelper calls this. If the intent is to save, then
891    * simply chanet that call to removeProperty(key).
892    *
893    * @param key
894    */
 
895  0 toggle public static void removePropertyNoSave(String key)
896    {
897   
898  0 getInstance().
899   
900    removePropertyImpl(key, false);
901    }
902   
903    /**
904    * Removes the named property, and optionally saves the current properties to
905    * file
906    *
907    * @param key
908    * @param andSave
909    */
 
910  30 toggle private void removePropertyImpl(String key, boolean andSave)
911    {
912  30 applicationProperties.remove(key);
913  30 if (andSave)
914  30 saveProperties();
915    }
916   
917    /**
918    * save the properties to the jalview properties path
919    */
 
920  30 toggle public static void saveProperties()
921    {
922  30 getInstance().savePropertiesImpl();
923    }
924   
925    /**
926    * save the properties to the jalview properties path
927    */
 
928  30 toggle private void savePropertiesImpl()
929   
930    {
931  30 if (!propsAreReadOnly)
932    {
933  0 try
934    {
935  0 FileOutputStream out = new FileOutputStream(propertiesFile);
936  0 applicationProperties.store(out, "---JalviewX Properties File---");
937  0 out.close();
938    } catch (Exception ex)
939    {
940  0 if (!Jalview.quiet())
941  0 jalview.bin.Console.errPrintln("Error saving properties: " + ex);
942    }
943    }
944    }
945   
946    /**
947    * internal vamsas class discovery state
948    */
949    private static int vamsasJarsArePresent = -1;
950   
951    /**
952    * Searches for vamsas client classes on class path.
953    *
954    * @return true if vamsas client is present on classpath
955    */
 
956  0 toggle public static boolean vamsasJarsPresent()
957    {
958  0 if (vamsasJarsArePresent == -1)
959    {
960  0 try
961    {
962  0 if (jalview.jbgui.GDesktop.class.getClassLoader()
963    .loadClass("uk.ac.vamsas.client.VorbaId") != null)
964    {
965  0 Console.debug(
966    "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
967  0 vamsasJarsArePresent = 1;
968  0 JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
969    Console.getCachedLogLevel("logs.Vamsas.Level"));
970  0 JLoggerLog4j.addAppender(lvclient, Console.log,
971    JALVIEW_LOGGER_NAME);
972    // Tell the user that debug is enabled
973  0 lvclient.debug(ChannelProperties.getProperty("app_name")
974    + " Vamsas Client Debugging Output Follows.");
975    }
976    } catch (Exception e)
977    {
978  0 vamsasJarsArePresent = 0;
979  0 Console.debug("Vamsas Classes are not present");
980    }
981    }
982  0 return (vamsasJarsArePresent > 0);
983    }
984   
985    /**
986    * internal vamsas class discovery state
987    */
988    private static int groovyJarsArePresent = -1;
989   
990    /**
991    * Searches for vamsas client classes on class path.
992    *
993    * @return true if vamsas client is present on classpath
994    */
 
995  0 toggle public static boolean groovyJarsPresent()
996    {
997  0 if (groovyJarsArePresent == -1)
998    {
999  0 try
1000    {
1001  0 if (Cache.class.getClassLoader()
1002    .loadClass("groovy.lang.GroovyObject") != null)
1003    {
1004  0 Console.debug(
1005    "Found Groovy (groovy.lang.GroovyObject can be loaded)");
1006  0 groovyJarsArePresent = 1;
1007  0 JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
1008    Console.getCachedLogLevel("logs.Groovy.Level"));
1009  0 JLoggerLog4j.addAppender(lgclient, Console.log,
1010    JALVIEW_LOGGER_NAME);
1011    // Tell the user that debug is enabled
1012  0 lgclient.debug(ChannelProperties.getProperty("app_name")
1013    + " Groovy Client Debugging Output Follows.");
1014    }
1015    } catch (Error e)
1016    {
1017  0 groovyJarsArePresent = 0;
1018  0 Console.debug("Groovy Classes are not present", e);
1019    } catch (Exception e)
1020    {
1021  0 groovyJarsArePresent = 0;
1022  0 Console.debug("Groovy Classes are not present");
1023    }
1024    }
1025  0 return (groovyJarsArePresent > 0);
1026    }
1027   
1028    /**
1029    * Initialise the tracker if it is not done already.
1030    */
 
1031  1 toggle public static void initAnalytics()
1032    {
1033  1 Plausible.setEnabled(true);
1034   
1035  1 String appName = ChannelProperties.getProperty("app_name") + " Desktop";
1036  1 String version = Cache.getProperty("VERSION") + "_"
1037    + Cache.getDefault("BUILD_DATE", "unknown");
1038  1 String path;
1039    /* we don't want to encode ':' as "%3A" for backward compatibility with the UA setup
1040    try
1041    {
1042    path = "/" + String.join("/", URLEncoder.encode(appName, "UTF-8"),
1043    URLEncoder.encode(version, "UTF-8"),
1044    URLEncoder.encode(APPLICATION_STARTED, "UTF-8"));
1045    } catch (UnsupportedEncodingException e)
1046    {
1047    */
1048  1 List<String> pathParts = new ArrayList<>();
1049  1 pathParts.add(appName);
1050  1 pathParts.add(version);
1051  1 pathParts.add(APPLICATION_STARTED);
1052  1 path = ("/" + String.join("/", pathParts)).replace(' ', '+');
1053    /*
1054    }
1055    */
1056  1 Plausible plausible = Plausible.getInstance();
1057   
1058    // This will send a new "application_launch" event with parameters
1059    // including the old-style "path", the channel name and version, and also
1060    // add the JSON string values to the querystring for logging reasons.
1061  1 plausible.sendEvent("application_launch", path, true, true);
1062    }
1063   
1064    private static final String APPLICATION_STARTED = "Application Started";
1065   
1066    /**
1067    * get the user's default colour if available
1068    *
1069    * @param property
1070    * @param defcolour
1071    * @return
1072    */
 
1073  130 toggle public static Color getDefaultColour(String property, Color defcolour)
1074    {
1075  130 String colprop = getProperty(property);
1076  130 if (colprop == null)
1077    {
1078  44 return defcolour;
1079    }
1080  86 Color col = ColorUtils.parseColourString(colprop);
1081  86 if (col == null)
1082    {
1083  0 Console.warn("Couldn't parse '" + colprop + "' as a colour for "
1084    + property);
1085    }
1086  86 return (col == null) ? defcolour : col;
1087    }
1088   
1089    /**
1090    * store a colour as a Jalview user default property
1091    *
1092    * @param property
1093    * @param colour
1094    */
 
1095  4 toggle public static void setColourPropertyNoSave(String property, Color colour)
1096    {
1097  4 setPropertyNoSave(property, jalview.util.Format.getHexString(colour));
1098    }
1099   
1100    /**
1101    * Stores a formatted date in a jalview property, using a fixed locale.
1102    *
1103    * @param propertyName
1104    * @param date
1105    * @return the formatted date string
1106    */
 
1107  132 toggle public static String setDateProperty(String propertyName, Date date)
1108    {
1109  132 String formatted = date_format.format(date);
1110  132 setProperty(propertyName, formatted);
1111  132 return formatted;
1112    }
1113   
1114    /**
1115    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1116    * format) and returns as a Date, or null if parsing fails
1117    *
1118    * @param propertyName
1119    * @return
1120    *
1121    */
 
1122  42 toggle public static Date getDateProperty(String propertyName)
1123    {
1124  42 String val = getProperty(propertyName);
1125   
1126  42 if (val != null)
1127    {
1128  42 try
1129    {
1130  ? if ((val = val.trim()).indexOf(",") < 0 && val.indexOf("-") >= 0
1131    && val.indexOf(" ") == val.lastIndexOf(" "))
1132    {
1133  0 val = val.replace(" ", ", ").replace('-', ' ');
1134    }
1135  42 Date date = date_format.parse(val);
1136  34 return date;
1137    } catch (Exception ex)
1138    {
1139  8 jalview.bin.Console
1140    .errPrintln("Invalid or corrupt date in property '"
1141    + propertyName + "' : value was '" + val + "'");
1142    }
1143    }
1144  8 return null;
1145    }
1146   
1147    /**
1148    * get and parse a property as an integer. send any parsing problems to
1149    * System.err
1150    *
1151    * @param property
1152    * @return null or Integer
1153    */
 
1154  87 toggle public static Integer getIntegerProperty(String property)
1155    {
1156  87 String val = getProperty(property);
1157  ? if (val != null && (val = val.trim()).length() > 0)
1158    {
1159  0 try
1160    {
1161  0 return Integer.valueOf(val);
1162    } catch (NumberFormatException x)
1163    {
1164  0 jalview.bin.Console.errPrintln("Invalid integer in property '"
1165    + property + "' (value was '" + val + "')");
1166    }
1167    }
1168  87 return null;
1169    }
1170   
1171    /**
1172    * Set the specified value, or remove it if null or empty. Does not save the
1173    * properties file.
1174    *
1175    * @param propName
1176    * @param value
1177    */
 
1178  3 toggle public static void setOrRemove(String propName, String value)
1179    {
1180  3 if (propName == null)
1181    {
1182  0 return;
1183    }
1184  3 if (value == null || value.trim().length() < 1)
1185    {
1186  0 getInstance().applicationProperties.remove(propName);
1187    }
1188    else
1189    {
1190  3 getInstance().applicationProperties.setProperty(propName, value);
1191    }
1192    }
1193   
1194    /**
1195    * Loads in user colour schemes from files.
1196    *
1197    * @param files
1198    * a '|'-delimited list of file paths
1199    */
 
1200  320 toggle public static void initUserColourSchemes(String files)
1201    {
1202  320 if (files == null || files.length() == 0)
1203    {
1204  320 return;
1205    }
1206   
1207    // In case colours can't be loaded, we'll remove them
1208    // from the default list here.
1209  0 StringBuffer coloursFound = new StringBuffer();
1210  0 StringTokenizer st = new StringTokenizer(files, "|");
1211  0 while (st.hasMoreElements())
1212    {
1213  0 String file = st.nextToken();
1214  0 try
1215    {
1216  0 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1217  0 if (ucs != null)
1218    {
1219  0 if (coloursFound.length() > 0)
1220    {
1221  0 coloursFound.append("|");
1222    }
1223  0 coloursFound.append(file);
1224  0 ColourSchemes.getInstance().registerColourScheme(ucs);
1225    }
1226    } catch (Exception ex)
1227    {
1228  0 if (!Jalview.quiet())
1229  0 jalview.bin.Console
1230    .outPrintln("Error loading User ColourFile\n" + ex);
1231    }
1232    }
1233  0 if (!files.equals(coloursFound.toString()))
1234    {
1235  0 if (coloursFound.toString().length() > 1)
1236    {
1237  0 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1238    coloursFound.toString());
1239    }
1240    else
1241    {
1242  0 getInstance().applicationProperties
1243    .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1244    }
1245    }
1246    }
1247   
1248    /**
1249    * Initial logging information helper for various versions output
1250    *
1251    * @param prefix
1252    * @param value
1253    * @param defaultValue
1254    */
 
1255  2086 toggle private static void appendIfNotNull(StringBuilder sb, String prefix,
1256    String value, String suffix, String defaultValue)
1257    {
1258  2086 if (value == null && defaultValue == null)
1259    {
1260  1341 return;
1261    }
1262  745 if (prefix != null)
1263  745 sb.append(prefix);
1264  745 sb.append(value == null ? defaultValue : value);
1265  745 if (suffix != null)
1266  745 sb.append(suffix);
1267    }
1268   
1269    /**
1270    *
1271    * @return Jalview version, build details and JVM platform version for console
1272    */
 
1273  149 toggle public static String getVersionDetailsForConsole()
1274    {
1275  149 boolean extra = Console.isDebugEnabled()
1276    || !"release".equals(ChannelProperties.getProperty("channel"));
1277  149 StringBuilder sb = new StringBuilder();
1278  149 sb.append(ChannelProperties.getProperty("app_name"))
1279    .append(" Version: ");
1280  149 sb.append(Cache.getDefault("VERSION", "TEST"));
1281  149 sb.append("\n");
1282  149 sb.append(ChannelProperties.getProperty("app_name"))
1283    .append(" Installation: ");
1284  149 sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1285  149 sb.append("\n");
1286  149 appendIfNotNull(sb, "Channel: ",
1287    ChannelProperties.getProperty("channel"), "\n", null);
1288  149 sb.append("Build Date: ");
1289  149 sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1290  149 sb.append("\n");
1291  149 if (extra)
1292    {
1293  149 appendIfNotNull(sb, "Preferences file: ", propertiesFile, "\n",
1294    "unknown");
1295  149 appendIfNotNull(sb, "Log file: ",
1296    System.getProperty("installer.logfile"), "\n", "unknown");
1297    }
1298  149 sb.append("Java version: ");
1299  149 sb.append(System.getProperty("java.version"));
1300  149 sb.append("\n");
1301  149 if (extra)
1302    {
1303  149 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1304    "\n", "unknown");
1305  149 appendIfNotNull(sb, "Java launch class: ",
1306    System.getProperty("sun.java.command"), "\n", "unknown");
1307  149 sb.append("Java platform: ");
1308  149 sb.append(System.getProperty("os.name"));
1309  149 sb.append(" ");
1310  149 sb.append(System.getProperty("os.version"));
1311  149 sb.append(" (");
1312  149 sb.append(System.getProperty("os.arch"));
1313  149 sb.append(")");
1314  149 sb.append("\n");
1315  149 LookAndFeel laf = UIManager.getLookAndFeel();
1316  149 String lafName = laf == null ? "Not obtained" : laf.getName();
1317  149 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1318  149 sb.append("Java LAF: ");
1319  149 sb.append(lafName);
1320  149 sb.append(" (");
1321  149 sb.append(lafClass);
1322  149 sb.append(")\n");
1323    // pid() only available in Java 9+
1324  149 if (LaunchUtils.getJavaVersion() > 8)
1325    {
1326  149 sb.append("Java Virtual Machine PID: ");
1327  149 sb.append(ProcessHandle.current().pid());
1328  149 sb.append("\n");
1329    }
1330   
1331    }
1332  149 appendIfNotNull(sb, "Installer version: ",
1333    System.getProperty("sys.install4jVersion"), "\n", null);
1334  149 if (extra)
1335    {
1336  149 String installerAppdir = System.getProperty("installer.appdir");
1337  149 if (installerAppdir != null)
1338    {
1339  0 try
1340    {
1341  0 String temp = new File(installerAppdir).getCanonicalPath();
1342  0 installerAppdir = temp;
1343    } catch (IOException e)
1344    {
1345  0 installerAppdir = "(non-canonical) " + installerAppdir;
1346  0 Console.warn(
1347    "Could not get canonical path for installer appdir, leaving as is.");
1348    }
1349    }
1350  149 appendIfNotNull(sb, "Installer template version: ",
1351    System.getProperty("installer.template_version"), "\n", null);
1352  149 appendIfNotNull(sb, "Installer appdir: ", installerAppdir, "\n",
1353    null);
1354  149 appendIfNotNull(sb, "Installer extrainfo: ",
1355    System.getProperty("installer.extrainfo"), "\n", null);
1356    }
1357  149 appendIfNotNull(sb, "Launcher version: ",
1358    System.getProperty("launcher.version"), "\n", null);
1359  149 if (extra)
1360    {
1361  149 appendIfNotNull(sb, "Launcher appdir: ",
1362    System.getProperty("launcher.appdir"), "\n", null);
1363  149 appendIfNotNull(sb, "Launcher distdir: ",
1364    System.getProperty("launcher.distdir"), "\n", null);
1365  149 appendIfNotNull(sb, "Launcher appbase: ",
1366    System.getProperty("launcher.appbase"), "\n", null);
1367  149 appendIfNotNull(sb, "Launcher script: ",
1368    System.getProperty("launcher.script"), "\n", null);
1369    }
1370  149 return sb.toString();
1371    }
1372   
1373    /**
1374    *
1375    * @return build details as reported in splashscreen
1376    */
 
1377  22 toggle public static String getBuildDetailsForSplash()
1378    {
1379    // consider returning more human friendly info
1380    // eg 'built from Source' or update channel
1381  22 return Cache.getDefault("INSTALLATION", "unknown");
1382    }
1383   
1384    /**
1385    *
1386    * For AppletParams and Preferences ok_actionPerformed and
1387    * startupFileTextfield_mouseClicked
1388    *
1389    * Sets a property value for the running application, without saving it to the
1390    * properties file
1391    *
1392    * @param key
1393    * @param obj
1394    */
 
1395  194 toggle public static void setPropertyNoSave(String key, String obj)
1396    {
1397  194 getInstance().setPropertyImpl(key, obj, false);
1398    }
1399   
1400    /**
1401    * Sets a property value, and optionally also saves the current properties to
1402    * file
1403    *
1404    * @param key
1405    * @param obj
1406    * @param andSave
1407    * @return
1408    */
 
1409  2553 toggle private Object setPropertyImpl(String key, String obj, boolean andSave)
1410    {
1411  2553 Object oldValue = null;
1412  2553 try
1413    {
1414  2553 oldValue = applicationProperties.setProperty(key, obj);
1415  2553 if (andSave && !propsAreReadOnly && propertiesFile != null
1416    // don't rewrite if new value is same as old value
1417    && !((obj == null && oldValue == null)
1418    || (obj != null && obj.equals(oldValue))))
1419    {
1420  16 FileOutputStream out = new FileOutputStream(propertiesFile);
1421  16 applicationProperties.store(out, "---JalviewX Properties File---");
1422  16 out.close();
1423    }
1424    } catch (Exception ex)
1425    {
1426  0 System.out.println(
1427    "Error setting property: " + key + " " + obj + "\n" + ex);
1428    }
1429  2553 return oldValue;
1430    }
1431   
 
1432  0 toggle public static String getStackTraceString(Throwable t)
1433    {
1434  0 StringWriter sw = new StringWriter();
1435  0 PrintWriter pw = new PrintWriter(sw);
1436  0 t.printStackTrace(pw);
1437  0 return sw.toString();
1438    }
1439   
1440    // proxy properties methods
 
1441  0 toggle public static void clearProxyProperties()
1442    {
1443  0 setProxyProperties(null, null, null, null, null, null, null, null,
1444    null);
1445    }
1446   
 
1447  320 toggle public static void resetProxyProperties()
1448    {
1449  320 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1450    startupProxyProperties[2], startupProxyProperties[3],
1451    startupProxyProperties[4],
1452  320 startupProxyProperties[5] == null ? null
1453    : startupProxyProperties[5].toCharArray(),
1454    startupProxyProperties[6],
1455  320 startupProxyProperties[7] == null ? null
1456    : startupProxyProperties[7].toCharArray(),
1457    startupProxyProperties[8]);
1458  320 StringBuilder sb = new StringBuilder();
1459  320 sb.append("Setting proxy properties to: http.proxyHost=")
1460    .append(startupProxyProperties[0]).append(", http.proxyPort=")
1461    .append(startupProxyProperties[1])
1462  320 .append(startupProxyProperties[4] != null
1463    && !startupProxyProperties[4].isEmpty()
1464    ? " [" + startupProxyProperties[4] + "]"
1465    : "")
1466    .append(", https.proxyHost=").append(startupProxyProperties[2])
1467    .append(", https.proxyPort=").append(startupProxyProperties[3])
1468  320 .append(startupProxyProperties[6] != null
1469    && !startupProxyProperties[6].isEmpty()
1470    ? " [" + startupProxyProperties[6] + "]"
1471    : "");
1472   
1473  320 Console.debug(sb.toString());
1474    }
1475   
 
1476  93 toggle public static void setProxyPropertiesFromPreferences()
1477    {
1478  93 setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1479    }
1480   
 
1481  93 toggle public static void setProxyPropertiesFromPreferences(
1482    String previousProxyType)
1483    {
1484  93 String proxyType = Cache.getDefault("USE_PROXY",
1485    Cache.PROXYTYPE_SYSTEM);
1486  93 if (previousProxyType != null
1487    && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1488    // customProxy
1489    && proxyType.equals(previousProxyType))
1490    {
1491    // no change
1492  93 return;
1493    }
1494  0 switch (proxyType)
1495    {
1496  0 case Cache.PROXYTYPE_NONE:
1497  0 if (!previousProxyType.equals(proxyType))
1498    {
1499  0 Console.info("Setting no proxy settings");
1500  0 Cache.setProxyProperties(null, null, null, null, null, null, null,
1501    null, null);
1502    }
1503  0 break;
1504  0 case Cache.PROXYTYPE_CUSTOM:
1505    // always re-set a custom proxy -- it might have changed, particularly
1506    // password
1507  0 Console.info("Setting custom proxy settings");
1508  0 boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1509  0 Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1510    Cache.getDefault("PROXY_PORT", null),
1511    Cache.getDefault("PROXY_SERVER_HTTPS", null),
1512    Cache.getDefault("PROXY_PORT_HTTPS", null),
1513  0 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1514    : null,
1515  0 proxyAuthSet ? Cache.proxyAuthPassword : null,
1516  0 proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1517    : null,
1518  0 proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1519  0 break;
1520  0 default: // system proxy settings by default
1521  0 Console.info("Setting system proxy settings");
1522  0 Cache.resetProxyProperties();
1523    }
1524    }
1525   
 
1526  320 toggle public static void setProxyProperties(String httpHost, String httpPort,
1527    String httpsHost, String httpsPort, String httpUser,
1528    char[] httpPassword, String httpsUser, char[] httpsPassword,
1529    String nonProxyHosts)
1530    {
1531  320 setOrClearSystemProperty("http.proxyHost", httpHost);
1532  320 setOrClearSystemProperty("http.proxyPort", httpPort);
1533  320 setOrClearSystemProperty("https.proxyHost", httpsHost);
1534  320 setOrClearSystemProperty("https.proxyPort", httpsPort);
1535  320 setOrClearSystemProperty("http.proxyUser", httpUser);
1536  320 setOrClearSystemProperty("https.proxyUser", httpsUser);
1537    // note: passwords for http.proxyPassword and https.proxyPassword are sent
1538    // via the Authenticator, properties do not need to be set
1539   
1540    // are we using a custom proxy (password prompt might be required)?
1541  320 boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1542    .equals(PROXYTYPE_CUSTOM);
1543   
1544    /*
1545    * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1546    * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1547    * is not re-called).
1548    * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1549    * the AuthCache.
1550    * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1551    * ...
1552    * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1553    */
1554    /*
1555    try
1556    {
1557    sun.net.www.protocol.http.AuthCacheValue
1558    .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1559    } catch (Throwable t)
1560    {
1561    Cache.error(t.getMessage());
1562    Cache.debug(getStackTraceString(t));
1563    }
1564    */
1565   
1566  320 if (httpUser != null || httpsUser != null)
1567    {
1568  0 try
1569    {
1570  0 char[] displayHttpPw = new char[httpPassword == null ? 0
1571    : httpPassword.length];
1572  0 Arrays.fill(displayHttpPw, '*');
1573  0 Console.debug(
1574    "CACHE Proxy: setting new Authenticator with httpUser='"
1575    + httpUser + "' httpPassword='" + displayHttpPw
1576    + "'");
1577  0 if (!Platform.isJS())
1578    /* *
1579    * java.net.Authenticator not implemented in SwingJS yet
1580    *
1581    * @j2sIgnore
1582    *
1583    */
1584    {
1585  0 Authenticator.setDefault(new Authenticator()
1586    {
 
1587  0 toggle @Override
1588    protected PasswordAuthentication getPasswordAuthentication()
1589    {
1590  0 if (getRequestorType() == RequestorType.PROXY)
1591    {
1592  0 String protocol = getRequestingProtocol();
1593  0 boolean needProxyPasswordSet = false;
1594  0 if (customProxySet &&
1595    // we have a username but no password for the scheme being
1596    // requested
1597    (protocol.equalsIgnoreCase("http")
1598    && (httpUser != null
1599    && httpUser.length() > 0
1600    && (httpPassword == null
1601    || httpPassword.length == 0)))
1602    || (protocol.equalsIgnoreCase("https")
1603    && (httpsUser != null
1604    && httpsUser.length() > 0
1605    && (httpsPassword == null
1606    || httpsPassword.length == 0))))
1607    {
1608    // open Preferences -> Connections
1609  0 String message = MessageManager
1610    .getString("label.proxy_password_required");
1611  0 Preferences.openPreferences(
1612    Preferences.TabRef.CONNECTIONS_TAB, message);
1613  0 Preferences.getInstance()
1614    .proxyAuthPasswordCheckHighlight(true, true);
1615    }
1616    else
1617    {
1618  0 try
1619    {
1620  0 if (protocol.equalsIgnoreCase("http")
1621    && getRequestingHost()
1622    .equalsIgnoreCase(httpHost)
1623    && getRequestingPort() == Integer
1624    .valueOf(httpPort))
1625    {
1626  0 Console.debug(
1627    "AUTHENTICATOR returning PasswordAuthentication(\""
1628    + httpUser + "\", '"
1629    + new String(displayHttpPw) + "')");
1630  0 return new PasswordAuthentication(httpUser,
1631    httpPassword);
1632    }
1633  0 if (protocol.equalsIgnoreCase("https")
1634    && getRequestingHost()
1635    .equalsIgnoreCase(httpsHost)
1636    && getRequestingPort() == Integer
1637    .valueOf(httpsPort))
1638    {
1639  0 char[] displayHttpsPw = new char[httpPassword.length];
1640  0 Arrays.fill(displayHttpsPw, '*');
1641  0 Console.debug(
1642    "AUTHENTICATOR returning PasswordAuthentication(\""
1643    + httpsUser + "\", '" + displayHttpsPw
1644    + "'");
1645  0 return new PasswordAuthentication(httpsUser,
1646    httpsPassword);
1647    }
1648    } catch (NumberFormatException e)
1649    {
1650  0 Console.error("Problem with proxy port values [http:"
1651    + httpPort + ", https:" + httpsPort + "]");
1652    }
1653  0 Console.debug(
1654    "AUTHENTICATOR after trying to get PasswordAuthentication");
1655    }
1656    }
1657    // non proxy request
1658  0 Console.debug("AUTHENTICATOR returning null");
1659  0 return null;
1660    }
1661    });
1662    } // end of j2sIgnore for java.net.Authenticator
1663   
1664    // required to re-enable basic authentication (should be okay for a
1665    // local proxy)
1666  0 Console.debug(
1667    "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1668  0 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1669    } catch (SecurityException e)
1670    {
1671  0 Console.error("Could not set default Authenticator");
1672  0 Console.debug(getStackTraceString(e));
1673    }
1674    }
1675    else
1676    {
1677    // reset the Authenticator to protect http.proxyUser and
1678    // http.proxyPassword Just In Case
1679    /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1680    * has working credentials. No workaround for Java 11.
1681    */
1682  320 if (!Platform.isJS())
1683    /* *
1684    * java.net.Authenticator not implemented in SwingJS yet
1685    *
1686    * @j2sIgnore
1687    *
1688    */
1689    {
1690  320 Console.debug(
1691    "AUTHENTICATOR setting default Authenticator to null");
1692  320 Authenticator.setDefault(null);
1693    }
1694    }
1695   
1696    // nonProxyHosts not currently configurable in Preferences
1697  320 Console.debug(
1698    "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1699    + nonProxyHosts + "\"");
1700  320 setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1701    }
1702   
 
1703  0 toggle public static void setOrClearSystemProperty(String key, char[] value)
1704    {
1705  0 setOrClearSystemProperty(key,
1706  0 (value == null) ? null : new String(value));
1707    }
1708   
 
1709  2240 toggle public static void setOrClearSystemProperty(String key, String value)
1710    {
1711  2240 if (key == null)
1712    {
1713  0 return;
1714    }
1715  2240 if (value == null)
1716    {
1717  2240 System.clearProperty(key);
1718    }
1719    else
1720    {
1721  0 System.setProperty(key, value);
1722    }
1723    }
1724   
1725    /**
1726    * Getdown appbase methods
1727    */
1728   
1729    private static final String releaseAppbase;
1730   
1731    private static String getdownAppbase;
1732   
1733    private static String getdownDistDir;
1734   
 
1735  55 toggle static
1736    {
1737  55 if (!Platform.isJS())
1738    {
1739  55 Float specversion = Float
1740    .parseFloat(System.getProperty("java.specification.version"));
1741  55 releaseAppbase = (specversion < 9)
1742    ? "https://www.jalview.org/getdown/release/1.8"
1743    : "https://www.jalview.org/getdown/release/11";
1744    }
1745    else
1746    {
1747    // this value currenly made up, can be changed to URL that will be
1748    // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1749  0 releaseAppbase = "https://www.jalview.org/jalview-js";
1750  0 getdownAppbase = releaseAppbase;
1751  0 getdownDistDir = "/swingjs/j2s";
1752    }
1753    }
1754   
1755    // look for properties (passed in by getdown) otherwise default to release
 
1756  131 toggle private static void setGetdownAppbase()
1757    {
1758  131 if (getdownAppbase != null)
1759    {
1760  113 return;
1761    }
1762  18 String appbase = System.getProperty("launcher.appbase");
1763  18 if (appbase == null)
1764    {
1765  18 appbase = System.getProperty("getdownappbase"); // old name
1766    }
1767  18 String distDir = System.getProperty("launcher.distdir");
1768  18 if (distDir == null)
1769    {
1770  18 distDir = System.getProperty("getdowndistdir"); // old name
1771    }
1772  18 if (appbase == null)
1773    {
1774  18 appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1775  18 distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1776    }
1777  18 if (appbase == null)
1778    {
1779  18 appbase = releaseAppbase;
1780  18 distDir = "release";
1781    }
1782  18 if (appbase.endsWith("/"))
1783    {
1784  0 appbase = appbase.substring(0, appbase.length() - 1);
1785    }
1786  18 if (distDir == null)
1787    {
1788  0 distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1789    }
1790  18 getdownAppbase = appbase;
1791  18 getdownDistDir = distDir;
1792    }
1793   
 
1794  131 toggle public static String getGetdownAppbase()
1795    {
1796  131 setGetdownAppbase();
1797  131 return getdownAppbase;
1798    }
1799   
 
1800  131 toggle public static String getAppbaseBuildProperties()
1801    {
1802  131 String appbase = getGetdownAppbase();
1803  131 return appbase + "/" + getdownDistDir + "/build_properties";
1804    }
1805   
1806    private static final Collection<String> bootstrapProperties = new ArrayList<>(
1807    Arrays.asList(JALVIEWLOGLEVEL, BOOTSTRAP_TEST));
1808   
 
1809  139 toggle public static Properties bootstrapProperties(String filename)
1810    {
1811  139 Properties bootstrapProps = new Properties();
1812  139 File file = null;
1813  139 if (filename != null)
1814    {
1815  48 file = new File(filename);
1816    }
1817  139 if (file == null || !file.exists())
1818    {
1819  91 if (file != null)
1820    {
1821  0 jalview.bin.Console
1822    .errPrintln("Could not load bootstrap preferences file '"
1823    + file.getPath() + "'");
1824    }
1825  91 String channelPrefsFilename = ChannelProperties
1826    .getProperty("preferences.filename");
1827  91 String propertiesFilename = System.getProperty("user.home")
1828    + File.separatorChar + channelPrefsFilename;
1829  91 jalview.bin.Console.errPrintln(
1830    "Using default properties file '" + propertiesFilename + "'");
1831  91 file = new File(propertiesFilename);
1832    }
1833  139 if (file == null || !file.exists())
1834   
1835    {
1836  0 String releasePrefsFilename = fallbackPropertiesFile;
1837  0 String releasePropertiesFilename = System.getProperty("user.home")
1838    + File.separatorChar + releasePrefsFilename;
1839  0 jalview.bin.Console.errPrintln("Falling back to properties file '"
1840    + releasePropertiesFilename + "'");
1841  0 file = new File(releasePropertiesFilename);
1842    }
1843   
1844  139 if (!file.exists())
1845    {
1846  0 jalview.bin.Console
1847    .errPrintln("Could not load bootstrap preferences file '"
1848    + file.getPath() + "'");
1849  0 return null;
1850    }
1851   
1852  139 try
1853    {
1854  139 FileInputStream in = new FileInputStream(file.getAbsoluteFile());
1855  139 Properties props = new Properties();
1856  139 props.load(in);
1857  139 for (String prop : bootstrapProperties)
1858    {
1859  278 if (props.containsKey(prop))
1860  9 bootstrapProps.put(prop, props.getProperty(prop));
1861    }
1862    } catch (FileNotFoundException e)
1863    {
1864  0 jalview.bin.Console
1865    .errPrintln("Could not find bootstrap preferences file '"
1866    + file.getAbsolutePath() + "'");
1867    } catch (IOException e)
1868    {
1869  0 jalview.bin.Console.errPrintln(
1870    "IOException when loading bootstrap preferences file '"
1871    + file.getAbsolutePath() + "'");
1872    }
1873  139 return bootstrapProps;
1874    }
1875   
 
1876  0 toggle public static void setSessionProperty(String key, String val)
1877    {
1878  0 if (key != null)
1879    {
1880  0 getInstance().sessionProperties.put(key, val);
1881    }
1882    }
1883   
 
1884  544736 toggle public static String getSessionProperty(String key)
1885    {
1886  544736 return key == null ? null : getInstance().sessionProperties.get(key);
1887    }
1888   
 
1889  11 toggle public static boolean getArgCacheDefault(Arg a, String pref, boolean def)
1890    {
1891  11 ArgParser ap = Jalview.getInstance().getArgParser();
1892  11 return (ap != null && ap.isSet(a)) ? ap.getBoolean(a)
1893    : getDefault(pref, def);
1894    }
1895    }