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