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