JAL-629 Fasta sequence id reading whitespace fix. Flexioble pae json keys and structu...
[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   public static boolean isPropsAreReadOnly()
326   {
327     return propsAreReadOnly;
328   }
329
330   public static void setPropsAreReadOnly(boolean propsAreReadOnly)
331   {
332     Cache.propsAreReadOnly = propsAreReadOnly;
333   }
334
335   private final static String JS_PROPERTY_PREFIX = "jalview_";
336
337   /**
338    * Loads properties from the given properties file. Any existing properties
339    * are first cleared.
340    */
341   public static void loadProperties(String propsFile)
342   {
343     propertiesFile = propsFile;
344     String releasePropertiesFile = null;
345     boolean defaultProperties = false;
346     if (propsFile == null && !propsAreReadOnly)
347     {
348       String channelPrefsFilename = ChannelProperties
349               .getProperty("preferences.filename");
350       String releasePrefsFilename = ".jalview_properties";
351       propertiesFile = System.getProperty("user.home") + File.separatorChar
352               + channelPrefsFilename;
353       releasePropertiesFile = System.getProperty("user.home")
354               + File.separatorChar + releasePrefsFilename;
355       defaultProperties = true;
356     }
357     else
358     {
359       // don't corrupt the file we've been given.
360       propsAreReadOnly = true;
361     }
362
363     if (propertiesFile == null)
364     { // BH 2019
365       Platform.readInfoProperties(JS_PROPERTY_PREFIX,
366               applicationProperties);
367     }
368     else
369     {
370       try
371       {
372         InputStream fis;
373         try
374         {
375           // props file provided as URL
376           fis = new URL(propertiesFile).openStream();
377           System.out.println(
378                   "Loading jalview properties from : " + propertiesFile);
379           System.out.println(
380                   "Disabling Jalview writing to user's local properties file.");
381           propsAreReadOnly = true;
382         } catch (Exception ex)
383         {
384           fis = null;
385         }
386         if (fis == null)
387         {
388           String readPropertiesFile = propertiesFile;
389           // if we're using the usual properties file and the channel properties
390           // file doesn't exist, read .jalview_properties
391           // (but we'll still save to the channel properties file).
392           if (defaultProperties && (!new File(propertiesFile).exists())
393                   && (new File(releasePropertiesFile).exists()))
394           {
395             readPropertiesFile = releasePropertiesFile;
396           }
397           fis = new FileInputStream(readPropertiesFile);
398         }
399         applicationProperties.clear();
400         applicationProperties.load(fis);
401
402         // remove any old build properties
403
404         deleteBuildProperties();
405         fis.close();
406       } catch (Exception ex)
407       {
408         System.out.println("Error reading properties file: " + ex);
409       }
410     }
411
412     /* TO BE REPLACED WITH PROXY_TYPE SETTINGS 
413     if (getDefault("USE_PROXY", false))
414     {
415       String proxyServer = getDefault("PROXY_SERVER", ""),
416               proxyPort = getDefault("PROXY_PORT", "8080");
417     }
418     */
419
420     // PROXY TYPE settings (now three options "none", "false", "true", but using
421     // backward compatible strings)
422     String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
423     // default to upgrading old settings
424     switch (proxyType)
425     {
426     case PROXYTYPE_NONE:
427       clearProxyProperties();
428       break;
429     case PROXYTYPE_SYSTEM: // use system settings
430       resetProxyProperties();
431       break;
432     case PROXYTYPE_CUSTOM: // use specified proxy settings
433       String httpHost = getDefault("PROXY_SERVER", "");
434       String httpPort = getDefault("PROXY_PORT", "8080");
435       String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
436       String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
437       String httpUser = getDefault("PROXY_AUTH_USER", null);
438       // https.proxyUser and https.proxyPassword are not able to be
439       // independently set in Preferences yet (or http.nonProxyHosts)
440       String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
441       setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
442               proxyAuthPassword, httpsUser, proxyAuthPassword, "localhost");
443       break;
444     default:
445       String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
446               + proxyType;
447       Console.warn(message);
448     }
449
450     // LOAD THE AUTHORS FROM THE authors.props file
451     String authorDetails = resolveResourceURLFor("/authors.props");
452
453     try
454     {
455       if (authorDetails != null)
456       {
457         URL localJarFileURL = new URL(authorDetails);
458         InputStream in = localJarFileURL.openStream();
459         applicationProperties.load(in);
460         in.close();
461       }
462     } catch (Exception ex)
463     {
464       System.out.println("Error reading author details: " + ex);
465       authorDetails = null;
466     }
467     if (authorDetails == null)
468     {
469       applicationProperties.remove("AUTHORS");
470       applicationProperties.remove("AUTHORFNAMES");
471       applicationProperties.remove("YEAR");
472     }
473
474     loadBuildProperties(false);
475
476     SiftsSettings
477             .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
478
479     SiftsSettings.setSiftDownloadDirectory(Cache
480             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
481
482     SiftsSettings.setFailSafePIDThreshold(
483             Cache.getDefault("sifts_fail_safe_pid_threshold",
484                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
485
486     SiftsSettings.setCacheThresholdInDays(
487             Cache.getDefault("sifts_cache_threshold_in_days",
488                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
489
490     IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
491             "https://www.jalview.org/services/identifiers"));
492     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
493
494     StructureImportSettings.setDefaultStructureFileFormat(
495             Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
496     StructureImportSettings
497             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
498     // StructureImportSettings
499     // .setDefaultPDBFileParser(Cache.getDefault(
500     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
501
502     String jnlpVersion = System.getProperty("jalview.version");
503
504     // jnlpVersion will be null if a latest version check for the channel needs
505     // to be done
506     // Dont do this check if running in headless mode
507
508     if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
509             && (System.getProperty("java.awt.headless") == null || System
510                     .getProperty("java.awt.headless").equals("false")))
511     {
512
513       class VersionChecker extends Thread
514       {
515
516         @Override
517         public void run()
518         {
519           String remoteBuildPropertiesUrl = Cache
520                   .getAppbaseBuildProperties();
521
522           String orgtimeout = System
523                   .getProperty("sun.net.client.defaultConnectTimeout");
524           if (orgtimeout == null)
525           {
526             orgtimeout = "30";
527             System.out.println("# INFO: Setting default net timeout to "
528                     + orgtimeout + " seconds.");
529           }
530           String remoteVersion = null;
531           if (remoteBuildPropertiesUrl.startsWith("http"))
532           {
533             try
534             {
535               System.setProperty("sun.net.client.defaultConnectTimeout",
536                       "5000");
537
538               URL url = new URL(remoteBuildPropertiesUrl);
539
540               BufferedReader in = new BufferedReader(
541                       new InputStreamReader(url.openStream()));
542
543               Properties remoteBuildProperties = new Properties();
544               remoteBuildProperties.load(in);
545               remoteVersion = remoteBuildProperties.getProperty("VERSION");
546             } catch (Exception ex)
547             {
548               System.out.println(
549                       "Non-fatal exception when checking version at "
550                               + remoteBuildPropertiesUrl + ":");
551               System.out.println(ex);
552               remoteVersion = getProperty("VERSION");
553             }
554           }
555           System.setProperty("sun.net.client.defaultConnectTimeout",
556                   orgtimeout);
557
558           setProperty("LATEST_VERSION", remoteVersion);
559         }
560       }
561
562       VersionChecker vc = new VersionChecker();
563       vc.start();
564     }
565     else
566     {
567       if (jnlpVersion != null)
568       {
569         setProperty("LATEST_VERSION", jnlpVersion);
570       }
571       else
572       {
573         applicationProperties.remove("LATEST_VERSION");
574       }
575     }
576
577     // LOAD USERDEFINED COLOURS
578     Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
579     jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
580             false);
581   }
582
583   /**
584    * construct a resource URL for the given absolute resource pathname
585    * 
586    * @param resourcePath
587    * @return
588    */
589   private static String resolveResourceURLFor(String resourcePath)
590   {
591     String url = null;
592     if (Platform.isJS() || !Cache.class.getProtectionDomain()
593             .getCodeSource().getLocation().toString().endsWith(".jar"))
594     {
595       try
596       {
597         url = Cache.class.getResource(resourcePath).toString();
598       } catch (Exception ex)
599       {
600         System.err.println("Failed to resolve resource " + resourcePath
601                 + ": " + ex.getMessage());
602       }
603     }
604     else
605     {
606       url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
607               .getLocation().toString().concat("!" + resourcePath));
608     }
609     return url;
610   }
611
612   public static void loadBuildProperties(boolean reportVersion)
613   {
614     String codeInstallation = getProperty("INSTALLATION");
615     boolean printVersion = codeInstallation == null;
616
617     /*
618      * read build properties - from the Jalview jar for a Java distribution,
619      * or from codebase file in test or JalviewJS context
620      */
621     try
622     {
623       String buildDetails = resolveResourceURLFor("/.build_properties");
624       URL localJarFileURL = new URL(buildDetails);
625       InputStream in = localJarFileURL.openStream();
626       buildProperties.load(in);
627       in.close();
628       if (buildProperties.getProperty("BUILD_DATE", null) != null)
629       {
630         applicationProperties.put("BUILD_DATE",
631                 buildProperties.getProperty("BUILD_DATE"));
632       }
633       if (buildProperties.getProperty("INSTALLATION", null) != null)
634       {
635         applicationProperties.put("INSTALLATION",
636                 buildProperties.getProperty("INSTALLATION"));
637       }
638       if (buildProperties.getProperty("VERSION", null) != null)
639       {
640         applicationProperties.put("VERSION",
641                 buildProperties.getProperty("VERSION"));
642       }
643       if (buildProperties.getProperty("JAVA_COMPILE_VERSION", null) != null)
644       {
645         applicationProperties.put("JAVA_COMPILE_VERSION",
646                 buildProperties.getProperty("JAVA_COMPILE_VERSION"));
647       }
648     } catch (Exception ex)
649     {
650       System.out.println("Error reading build details: " + ex);
651       applicationProperties.remove("VERSION");
652     }
653     String codeVersion = getProperty("VERSION");
654     codeInstallation = getProperty("INSTALLATION");
655
656     if (codeVersion == null)
657     {
658       // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
659       codeVersion = "Test";
660       codeInstallation = "";
661     }
662     else
663     {
664       codeInstallation = " (" + codeInstallation + ")";
665     }
666     setProperty("VERSION", codeVersion);
667     new BuildDetails(codeVersion, null, codeInstallation);
668     if (printVersion && reportVersion)
669     {
670       System.out.println(ChannelProperties.getProperty("app_name")
671               + " Version: " + codeVersion + codeInstallation);
672     }
673   }
674
675   private static void deleteBuildProperties()
676   {
677     applicationProperties.remove("LATEST_VERSION");
678     applicationProperties.remove("VERSION");
679     applicationProperties.remove("AUTHORS");
680     applicationProperties.remove("AUTHORFNAMES");
681     applicationProperties.remove("YEAR");
682     applicationProperties.remove("BUILD_DATE");
683     applicationProperties.remove("INSTALLATION");
684   }
685
686   /**
687    * Gets Jalview application property of given key. Returns null if key not
688    * found
689    * 
690    * @param key
691    *          Name of property
692    * 
693    * @return Property value
694    */
695   public static String getProperty(String key)
696   {
697     String prop = applicationProperties.getProperty(key);
698     if (prop == null && Platform.isJS())
699     {
700       prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
701               + "_" + JS_PROPERTY_PREFIX + key);
702     }
703     return prop;
704   }
705
706   /**
707    * These methods are used when checking if the saved preference is different
708    * to the default setting
709    */
710
711   public static boolean getDefault(String property, boolean def)
712   {
713     String string = getProperty(property);
714     if (string != null)
715     {
716       def = Boolean.valueOf(string).booleanValue();
717     }
718
719     return def;
720   }
721
722   public static int getDefault(String property, int def)
723   {
724     String string = getProperty(property);
725     if (string != null)
726     {
727       try
728       {
729         def = Integer.parseInt(string);
730       } catch (NumberFormatException e)
731       {
732         System.out.println("Error parsing int property '" + property
733                 + "' with value '" + string + "'");
734       }
735     }
736
737     return def;
738   }
739
740   /**
741    * Answers the value of the given property, or the supplied default value if
742    * the property is not set
743    */
744   public static String getDefault(String property, String def)
745   {
746     String value = getProperty(property);
747     return value == null ? def : value;
748   }
749
750   /**
751    * Stores property in the file "HOME_DIR/.jalview_properties"
752    * 
753    * @param key
754    *          Name of object
755    * @param obj
756    *          String value of property
757    * 
758    * @return previous value of property (or null)
759    */
760   public static Object setProperty(String key, String obj)
761   {
762     Object oldValue = null;
763     try
764     {
765       oldValue = applicationProperties.setProperty(key, obj);
766       if (propertiesFile != null && !propsAreReadOnly)
767       {
768         FileOutputStream out = new FileOutputStream(propertiesFile);
769         applicationProperties.store(out, "---JalviewX Properties File---");
770         out.close();
771       }
772     } catch (Exception ex)
773     {
774       System.out.println(
775               "Error setting property: " + key + " " + obj + "\n" + ex);
776     }
777     return oldValue;
778   }
779
780   /**
781    * remove the specified property from the jalview properties file
782    * 
783    * @param string
784    */
785   public static void removeProperty(String string)
786   {
787     applicationProperties.remove(string);
788     saveProperties();
789   }
790
791   /**
792    * save the properties to the jalview properties path
793    */
794   public static void saveProperties()
795   {
796     if (!propsAreReadOnly)
797     {
798       try
799       {
800         FileOutputStream out = new FileOutputStream(propertiesFile);
801         applicationProperties.store(out, "---JalviewX Properties File---");
802         out.close();
803       } catch (Exception ex)
804       {
805         System.out.println("Error saving properties: " + ex);
806       }
807     }
808   }
809
810   /**
811    * internal vamsas class discovery state
812    */
813   private static int vamsasJarsArePresent = -1;
814
815   /**
816    * Searches for vamsas client classes on class path.
817    * 
818    * @return true if vamsas client is present on classpath
819    */
820   public static boolean vamsasJarsPresent()
821   {
822     if (vamsasJarsArePresent == -1)
823     {
824       try
825       {
826         if (jalview.jbgui.GDesktop.class.getClassLoader()
827                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
828         {
829           Console.debug(
830                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
831           vamsasJarsArePresent = 1;
832           JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
833                   Console.getCachedLogLevel("logs.Vamsas.Level"));
834           JLoggerLog4j.addAppender(lvclient, Console.log,
835                   JALVIEW_LOGGER_NAME);
836           // Tell the user that debug is enabled
837           lvclient.debug(ChannelProperties.getProperty("app_name")
838                   + " Vamsas Client Debugging Output Follows.");
839         }
840       } catch (Exception e)
841       {
842         vamsasJarsArePresent = 0;
843         Console.debug("Vamsas Classes are not present");
844       }
845     }
846     return (vamsasJarsArePresent > 0);
847   }
848
849   /**
850    * internal vamsas class discovery state
851    */
852   private static int groovyJarsArePresent = -1;
853
854   /**
855    * Searches for vamsas client classes on class path.
856    * 
857    * @return true if vamsas client is present on classpath
858    */
859   public static boolean groovyJarsPresent()
860   {
861     if (groovyJarsArePresent == -1)
862     {
863       try
864       {
865         if (Cache.class.getClassLoader()
866                 .loadClass("groovy.lang.GroovyObject") != null)
867         {
868           Console.debug(
869                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
870           groovyJarsArePresent = 1;
871           JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
872                   Console.getCachedLogLevel("logs.Groovy.Level"));
873           JLoggerLog4j.addAppender(lgclient, Console.log,
874                   JALVIEW_LOGGER_NAME);
875           // Tell the user that debug is enabled
876           lgclient.debug(ChannelProperties.getProperty("app_name")
877                   + " Groovy Client Debugging Output Follows.");
878         }
879       } catch (Error e)
880       {
881         groovyJarsArePresent = 0;
882         Console.debug("Groovy Classes are not present", e);
883       } catch (Exception e)
884       {
885         groovyJarsArePresent = 0;
886         Console.debug("Groovy Classes are not present");
887       }
888     }
889     return (groovyJarsArePresent > 0);
890   }
891
892   /**
893    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
894    * enabled.
895    */
896   protected static Object tracker = null;
897
898   protected static Class trackerfocus = null;
899
900   protected static Class jgoogleanalyticstracker = null;
901
902   /**
903    * Initialise the google tracker if it is not done already.
904    */
905   public static void initGoogleTracker()
906   {
907     if (tracker == null)
908     {
909       if (jgoogleanalyticstracker == null)
910       {
911         // try to get the tracker class
912         try
913         {
914           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
915                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
916           trackerfocus = Cache.class.getClassLoader()
917                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
918         } catch (Exception e)
919         {
920           Console.debug(
921                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
922           tracker = null;
923           jgoogleanalyticstracker = null;
924           trackerfocus = null;
925           return;
926         }
927       }
928       // now initialise tracker
929       Exception re = null, ex = null;
930       Error err = null;
931       String vrs = "No Version Accessible";
932       try
933       {
934         // Google analytics tracking code for Library Finder
935         tracker = jgoogleanalyticstracker
936                 .getConstructor(new Class[]
937                 { String.class, String.class, String.class })
938                 .newInstance(new Object[]
939                 { ChannelProperties.getProperty("app_name") + " Desktop",
940                     (vrs = Cache.getProperty("VERSION") + "_"
941                             + Cache.getDefault("BUILD_DATE", "unknown")),
942                     "UA-9060947-1" });
943         jgoogleanalyticstracker
944                 .getMethod("trackAsynchronously", new Class[]
945                 { trackerfocus })
946                 .invoke(tracker, new Object[]
947                 { trackerfocus.getConstructor(new Class[] { String.class })
948                         .newInstance(new Object[]
949                         { "Application Started." }) });
950       } catch (RuntimeException e)
951       {
952         re = e;
953       } catch (Exception e)
954       {
955         ex = e;
956       } catch (Error e)
957       {
958         err = e;
959       }
960       if (re != null || ex != null || err != null)
961       {
962         if (re != null)
963         {
964           Console.debug("Caught runtime exception in googletracker init:",
965                   re);
966         }
967         if (ex != null)
968         {
969           Console.warn(
970                   "Failed to initialise GoogleTracker for Jalview Desktop with version "
971                           + vrs,
972                   ex);
973         }
974         if (err != null)
975         {
976           Console.error(
977                   "Whilst initing GoogleTracker for Jalview Desktop version "
978                           + vrs,
979                   err);
980         }
981       }
982       else
983       {
984         Console.debug("Successfully initialised tracker.");
985       }
986     }
987   }
988
989   /**
990    * get the user's default colour if available
991    * 
992    * @param property
993    * @param defcolour
994    * @return
995    */
996   public static Color getDefaultColour(String property, Color defcolour)
997   {
998     String colprop = getProperty(property);
999     if (colprop == null)
1000     {
1001       return defcolour;
1002     }
1003     Color col = ColorUtils.parseColourString(colprop);
1004     if (col == null)
1005     {
1006       Console.warn("Couldn't parse '" + colprop + "' as a colour for "
1007               + property);
1008     }
1009     return (col == null) ? defcolour : col;
1010   }
1011
1012   /**
1013    * store a colour as a Jalview user default property
1014    * 
1015    * @param property
1016    * @param colour
1017    */
1018   public static void setColourProperty(String property, Color colour)
1019   {
1020     setProperty(property, jalview.util.Format.getHexString(colour));
1021   }
1022
1023   /**
1024    * Stores a formatted date in a jalview property, using a fixed locale.
1025    * 
1026    * @param propertyName
1027    * @param date
1028    * @return the formatted date string
1029    */
1030   public static String setDateProperty(String propertyName, Date date)
1031   {
1032     String formatted = date_format.format(date);
1033     setProperty(propertyName, formatted);
1034     return formatted;
1035   }
1036
1037   /**
1038    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1039    * format) and returns as a Date, or null if parsing fails
1040    * 
1041    * @param propertyName
1042    * @return
1043    * 
1044    */
1045   public static Date getDateProperty(String propertyName)
1046   {
1047     String val = getProperty(propertyName);
1048     if (val != null)
1049     {
1050       try
1051       {
1052         return date_format.parse(val);
1053       } catch (Exception ex)
1054       {
1055         System.err.println("Invalid or corrupt date in property '"
1056                 + propertyName + "' : value was '" + val + "'");
1057       }
1058     }
1059     return null;
1060   }
1061
1062   /**
1063    * get and parse a property as an integer. send any parsing problems to
1064    * System.err
1065    * 
1066    * @param property
1067    * @return null or Integer
1068    */
1069   public static Integer getIntegerProperty(String property)
1070   {
1071     String val = getProperty(property);
1072     if (val != null && (val = val.trim()).length() > 0)
1073     {
1074       try
1075       {
1076         return Integer.valueOf(val);
1077       } catch (NumberFormatException x)
1078       {
1079         System.err.println("Invalid integer in property '" + property
1080                 + "' (value was '" + val + "')");
1081       }
1082     }
1083     return null;
1084   }
1085
1086   /**
1087    * Set the specified value, or remove it if null or empty. Does not save the
1088    * properties file.
1089    * 
1090    * @param propName
1091    * @param value
1092    */
1093   public static void setOrRemove(String propName, String value)
1094   {
1095     if (propName == null)
1096     {
1097       return;
1098     }
1099     if (value == null || value.trim().length() < 1)
1100     {
1101       Cache.applicationProperties.remove(propName);
1102     }
1103     else
1104     {
1105       Cache.applicationProperties.setProperty(propName, value);
1106     }
1107   }
1108
1109   /**
1110    * Loads in user colour schemes from files.
1111    * 
1112    * @param files
1113    *          a '|'-delimited list of file paths
1114    */
1115   public static void initUserColourSchemes(String files)
1116   {
1117     if (files == null || files.length() == 0)
1118     {
1119       return;
1120     }
1121
1122     // In case colours can't be loaded, we'll remove them
1123     // from the default list here.
1124     StringBuffer coloursFound = new StringBuffer();
1125     StringTokenizer st = new StringTokenizer(files, "|");
1126     while (st.hasMoreElements())
1127     {
1128       String file = st.nextToken();
1129       try
1130       {
1131         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1132         if (ucs != null)
1133         {
1134           if (coloursFound.length() > 0)
1135           {
1136             coloursFound.append("|");
1137           }
1138           coloursFound.append(file);
1139           ColourSchemes.getInstance().registerColourScheme(ucs);
1140         }
1141       } catch (Exception ex)
1142       {
1143         System.out.println("Error loading User ColourFile\n" + ex);
1144       }
1145     }
1146     if (!files.equals(coloursFound.toString()))
1147     {
1148       if (coloursFound.toString().length() > 1)
1149       {
1150         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1151                 coloursFound.toString());
1152       }
1153       else
1154       {
1155         applicationProperties
1156                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1157       }
1158     }
1159   }
1160
1161   /**
1162    * Initial logging information helper for various versions output
1163    * 
1164    * @param prefix
1165    * @param value
1166    * @param defaultValue
1167    */
1168   private static void appendIfNotNull(StringBuilder sb, String prefix,
1169           String value, String suffix, String defaultValue)
1170   {
1171     if (value == null && defaultValue == null)
1172     {
1173       return;
1174     }
1175     if (prefix != null)
1176       sb.append(prefix);
1177     sb.append(value == null ? defaultValue : value);
1178     if (suffix != null)
1179       sb.append(suffix);
1180   }
1181
1182   /**
1183    * 
1184    * @return Jalview version, build details and JVM platform version for console
1185    */
1186   public static String getVersionDetailsForConsole()
1187   {
1188     StringBuilder sb = new StringBuilder();
1189     sb.append(ChannelProperties.getProperty("app_name"))
1190             .append(" Version: ");
1191     sb.append(Cache.getDefault("VERSION", "TEST"));
1192     sb.append("\n");
1193     sb.append(ChannelProperties.getProperty("app_name"))
1194             .append(" Installation: ");
1195     sb.append(Cache.getDefault("INSTALLATION", "unknown"));
1196     sb.append("\n");
1197     sb.append("Build Date: ");
1198     sb.append(Cache.getDefault("BUILD_DATE", "unknown"));
1199     sb.append("\n");
1200     sb.append("Java version: ");
1201     sb.append(System.getProperty("java.version"));
1202     sb.append("\n");
1203     sb.append(System.getProperty("os.arch"));
1204     sb.append(" ");
1205     sb.append(System.getProperty("os.name"));
1206     sb.append(" ");
1207     sb.append(System.getProperty("os.version"));
1208     sb.append("\n");
1209     appendIfNotNull(sb, "Install4j version: ",
1210             System.getProperty("sys.install4jVersion"), "\n", null);
1211     appendIfNotNull(sb, "Install4j template version: ",
1212             System.getProperty("installer_template_version"), "\n", null);
1213     appendIfNotNull(sb, "Launcher version: ",
1214             System.getProperty("launcher_version"), "\n", null);
1215     LookAndFeel laf = UIManager.getLookAndFeel();
1216     String lafName = laf == null ? "Not obtained" : laf.getName();
1217     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1218     sb.append("LookAndFeel: ");
1219     sb.append(lafName);
1220     sb.append(" (");
1221     sb.append(lafClass);
1222     sb.append(")\n");
1223     if (Console.isDebugEnabled()
1224             || !"release".equals(ChannelProperties.getProperty("channel")))
1225     {
1226       appendIfNotNull(sb, "Channel: ",
1227               ChannelProperties.getProperty("channel"), "\n", null);
1228       appendIfNotNull(sb, "Getdown appdir: ",
1229               System.getProperty("getdowninstanceappdir"), "\n", null);
1230       appendIfNotNull(sb, "Getdown appbase: ",
1231               System.getProperty("getdowninstanceappbase"), "\n", null);
1232       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1233               "\n", "unknown");
1234     }
1235     return sb.toString();
1236   }
1237
1238   /**
1239    * 
1240    * @return build details as reported in splashscreen
1241    */
1242   public static String getBuildDetailsForSplash()
1243   {
1244     // consider returning more human friendly info
1245     // eg 'built from Source' or update channel
1246     return Cache.getDefault("INSTALLATION", "unknown");
1247   }
1248
1249   public static String getStackTraceString(Throwable t)
1250   {
1251     StringWriter sw = new StringWriter();
1252     PrintWriter pw = new PrintWriter(sw);
1253     t.printStackTrace(pw);
1254     return sw.toString();
1255   }
1256
1257   // proxy properties methods
1258   public static void clearProxyProperties()
1259   {
1260     setProxyProperties(null, null, null, null, null, null, null, null,
1261             null);
1262   }
1263
1264   public static void resetProxyProperties()
1265   {
1266     setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1267             startupProxyProperties[2], startupProxyProperties[3],
1268             startupProxyProperties[4],
1269             startupProxyProperties[5] == null ? null
1270                     : startupProxyProperties[5].toCharArray(),
1271             startupProxyProperties[6],
1272             startupProxyProperties[7] == null ? null
1273                     : startupProxyProperties[7].toCharArray(),
1274             startupProxyProperties[8]);
1275     StringBuilder sb = new StringBuilder();
1276     sb.append("Setting proxy properties to: http.proxyHost=")
1277             .append(startupProxyProperties[0]).append(", http.proxyPort=")
1278             .append(startupProxyProperties[1])
1279             .append(startupProxyProperties[4] != null
1280                     && !startupProxyProperties[4].isEmpty()
1281                             ? " [" + startupProxyProperties[4] + "]"
1282                             : "")
1283             .append(", https.proxyHost=").append(startupProxyProperties[2])
1284             .append(", https.proxyPort=").append(startupProxyProperties[3])
1285             .append(startupProxyProperties[6] != null
1286                     && !startupProxyProperties[6].isEmpty()
1287                             ? " [" + startupProxyProperties[6] + "]"
1288                             : "");
1289
1290     Console.debug(sb.toString());
1291   }
1292
1293   public static void setProxyPropertiesFromPreferences()
1294   {
1295     setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1296   }
1297
1298   public static void setProxyPropertiesFromPreferences(
1299           String previousProxyType)
1300   {
1301     String proxyType = Cache.getDefault("USE_PROXY",
1302             Cache.PROXYTYPE_SYSTEM);
1303     if (previousProxyType != null
1304             && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1305                                                          // customProxy
1306             && proxyType.equals(previousProxyType))
1307     {
1308       // no change
1309       return;
1310     }
1311     switch (proxyType)
1312     {
1313     case Cache.PROXYTYPE_NONE:
1314       if (!previousProxyType.equals(proxyType))
1315       {
1316         Console.info("Setting no proxy settings");
1317         Cache.setProxyProperties(null, null, null, null, null, null, null,
1318                 null, null);
1319       }
1320       break;
1321     case Cache.PROXYTYPE_CUSTOM:
1322       // always re-set a custom proxy -- it might have changed, particularly
1323       // password
1324       Console.info("Setting custom proxy settings");
1325       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1326       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1327               Cache.getDefault("PROXY_PORT", null),
1328               Cache.getDefault("PROXY_SERVER_HTTPS", null),
1329               Cache.getDefault("PROXY_PORT_HTTPS", null),
1330               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1331                       : null,
1332               proxyAuthSet ? Cache.proxyAuthPassword : null,
1333               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1334                       : null,
1335               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1336       break;
1337     default: // system proxy settings by default
1338       Console.info("Setting system proxy settings");
1339       Cache.resetProxyProperties();
1340     }
1341   }
1342
1343   public static void setProxyProperties(String httpHost, String httpPort,
1344           String httpsHost, String httpsPort, String httpUser,
1345           char[] httpPassword, String httpsUser, char[] httpsPassword,
1346           String nonProxyHosts)
1347   {
1348     setOrClearSystemProperty("http.proxyHost", httpHost);
1349     setOrClearSystemProperty("http.proxyPort", httpPort);
1350     setOrClearSystemProperty("https.proxyHost", httpsHost);
1351     setOrClearSystemProperty("https.proxyPort", httpsPort);
1352     setOrClearSystemProperty("http.proxyUser", httpUser);
1353     setOrClearSystemProperty("https.proxyUser", httpsUser);
1354     // note: passwords for http.proxyPassword and https.proxyPassword are sent
1355     // via the Authenticator, properties do not need to be set
1356
1357     // are we using a custom proxy (password prompt might be required)?
1358     boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1359             .equals(PROXYTYPE_CUSTOM);
1360
1361     /*
1362      * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1363      * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1364      * is not re-called).
1365      * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1366      * the AuthCache.
1367      * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1368      * ...
1369      * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1370      */
1371     /*
1372     try
1373     {
1374       sun.net.www.protocol.http.AuthCacheValue
1375               .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1376     } catch (Throwable t)
1377     {
1378       Cache.error(t.getMessage());
1379       Cache.debug(getStackTraceString(t));
1380     }
1381     */
1382
1383     if (httpUser != null || httpsUser != null)
1384     {
1385       try
1386       {
1387         char[] displayHttpPw = new char[httpPassword == null ? 0
1388                 : httpPassword.length];
1389         Arrays.fill(displayHttpPw, '*');
1390         Console.debug(
1391                 "CACHE Proxy: setting new Authenticator with httpUser='"
1392                         + httpUser + "' httpPassword='" + displayHttpPw
1393                         + "'");
1394         if (!Platform.isJS())
1395         /* *
1396          * java.net.Authenticator not implemented in SwingJS yet
1397          * 
1398          * @j2sIgnore
1399          * 
1400          */
1401         {
1402           Authenticator.setDefault(new Authenticator()
1403           {
1404             @Override
1405             protected PasswordAuthentication getPasswordAuthentication()
1406             {
1407               if (getRequestorType() == RequestorType.PROXY)
1408               {
1409                 String protocol = getRequestingProtocol();
1410                 boolean needProxyPasswordSet = false;
1411                 if (customProxySet &&
1412                 // we have a username but no password for the scheme being
1413                 // requested
1414                         (protocol.equalsIgnoreCase("http")
1415                                 && (httpUser != null
1416                                         && httpUser.length() > 0
1417                                         && (httpPassword == null
1418                                                 || httpPassword.length == 0)))
1419                         || (protocol.equalsIgnoreCase("https")
1420                                 && (httpsUser != null
1421                                         && httpsUser.length() > 0
1422                                         && (httpsPassword == null
1423                                                 || httpsPassword.length == 0))))
1424                 {
1425                   // open Preferences -> Connections
1426                   String message = MessageManager
1427                           .getString("label.proxy_password_required");
1428                   Preferences.openPreferences(
1429                           Preferences.TabRef.CONNECTIONS_TAB, message);
1430                   Preferences.getInstance()
1431                           .proxyAuthPasswordCheckHighlight(true, true);
1432                 }
1433                 else
1434                 {
1435                   try
1436                   {
1437                     if (protocol.equalsIgnoreCase("http")
1438                             && getRequestingHost()
1439                                     .equalsIgnoreCase(httpHost)
1440                             && getRequestingPort() == Integer
1441                                     .valueOf(httpPort))
1442                     {
1443                       Console.debug(
1444                               "AUTHENTICATOR returning PasswordAuthentication(\""
1445                                       + httpUser + "\", '"
1446                                       + new String(displayHttpPw) + "')");
1447                       return new PasswordAuthentication(httpUser,
1448                               httpPassword);
1449                     }
1450                     if (protocol.equalsIgnoreCase("https")
1451                             && getRequestingHost()
1452                                     .equalsIgnoreCase(httpsHost)
1453                             && getRequestingPort() == Integer
1454                                     .valueOf(httpsPort))
1455                     {
1456                       char[] displayHttpsPw = new char[httpPassword.length];
1457                       Arrays.fill(displayHttpsPw, '*');
1458                       Console.debug(
1459                               "AUTHENTICATOR returning PasswordAuthentication(\""
1460                                       + httpsUser + "\", '" + displayHttpsPw
1461                                       + "'");
1462                       return new PasswordAuthentication(httpsUser,
1463                               httpsPassword);
1464                     }
1465                   } catch (NumberFormatException e)
1466                   {
1467                     Console.error("Problem with proxy port values [http:"
1468                             + httpPort + ", https:" + httpsPort + "]");
1469                   }
1470                   Console.debug(
1471                           "AUTHENTICATOR after trying to get PasswordAuthentication");
1472                 }
1473               }
1474               // non proxy request
1475               Console.debug("AUTHENTICATOR returning null");
1476               return null;
1477             }
1478           });
1479         } // end of j2sIgnore for java.net.Authenticator
1480
1481         // required to re-enable basic authentication (should be okay for a
1482         // local proxy)
1483         Console.debug(
1484                 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1485         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1486       } catch (SecurityException e)
1487       {
1488         Console.error("Could not set default Authenticator");
1489         Console.debug(getStackTraceString(e));
1490       }
1491     }
1492     else
1493     {
1494       // reset the Authenticator to protect http.proxyUser and
1495       // http.proxyPassword Just In Case
1496       /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1497        * has working credentials. No workaround for Java 11.
1498        */
1499       if (!Platform.isJS())
1500       /* *
1501        * java.net.Authenticator not implemented in SwingJS yet
1502        * 
1503        * @j2sIgnore
1504        * 
1505        */
1506       {
1507         Console.debug(
1508                 "AUTHENTICATOR setting default Authenticator to null");
1509         Authenticator.setDefault(null);
1510       }
1511     }
1512
1513     // nonProxyHosts not currently configurable in Preferences
1514     Console.debug(
1515             "AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1516                     + nonProxyHosts + "\"");
1517     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1518   }
1519
1520   public static void setOrClearSystemProperty(String key, char[] value)
1521   {
1522     setOrClearSystemProperty(key,
1523             (value == null) ? null : new String(value));
1524   }
1525
1526   public static void setOrClearSystemProperty(String key, String value)
1527   {
1528     if (key == null)
1529     {
1530       return;
1531     }
1532     if (value == null)
1533     {
1534       System.clearProperty(key);
1535     }
1536     else
1537     {
1538       System.setProperty(key, value);
1539     }
1540   }
1541
1542   /**
1543    * Getdown appbase methods
1544    */
1545
1546   private static final String releaseAppbase;
1547
1548   private static String getdownAppbase;
1549
1550   private static String getdownDistDir;
1551
1552   static
1553   {
1554     if (!Platform.isJS())
1555     {
1556       Float specversion = Float
1557               .parseFloat(System.getProperty("java.specification.version"));
1558       releaseAppbase = (specversion < 9)
1559               ? "https://www.jalview.org/getdown/release/1.8"
1560               : "https://www.jalview.org/getdown/release/11";
1561     }
1562     else
1563     {
1564       // this value currenly made up, can be changed to URL that will be
1565       // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1566       releaseAppbase = "https://www.jalview.org/jalview-js";
1567       getdownAppbase = releaseAppbase;
1568       getdownDistDir = "/swingjs/j2s";
1569     }
1570   }
1571
1572   // look for properties (passed in by getdown) otherwise default to release
1573   private static void setGetdownAppbase()
1574   {
1575     if (getdownAppbase != null)
1576     {
1577       return;
1578     }
1579     String appbase = System.getProperty("getdownappbase");
1580     String distDir = System.getProperty("getdowndistdir");
1581     if (appbase == null)
1582     {
1583       appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1584       distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1585     }
1586     if (appbase == null)
1587     {
1588       appbase = releaseAppbase;
1589       distDir = "release";
1590     }
1591     if (appbase.endsWith("/"))
1592     {
1593       appbase = appbase.substring(0, appbase.length() - 1);
1594     }
1595     if (distDir == null)
1596     {
1597       distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1598     }
1599     getdownAppbase = appbase;
1600     getdownDistDir = distDir;
1601   }
1602
1603   public static String getGetdownAppbase()
1604   {
1605     setGetdownAppbase();
1606     return getdownAppbase;
1607   }
1608
1609   public static String getAppbaseBuildProperties()
1610   {
1611     String appbase = getGetdownAppbase();
1612     return appbase + "/" + getdownDistDir + "/build_properties";
1613   }
1614 }