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