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