JAL-3741 http to https (and jar to jvp for exampleFile defaults!)
[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 (https://www.jalview.org) a property enabling all HTTP
186  * requests to be redirected to a mirror of https://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 are
374    * 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             "https://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 found
714    * 
715    * @param key
716    *              Name of property
717    * 
718    * @return Property value
719    */
720   public static String getProperty(String key)
721   {
722     String prop = applicationProperties.getProperty(key);
723     if (prop == null && Platform.isJS())
724     {
725       prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
726               + "_" + JS_PROPERTY_PREFIX + key);
727     }
728     return prop;
729   }
730
731   /**
732    * These methods are used when checking if the saved preference is different to
733    * the default setting
734    */
735
736   public static boolean getDefault(String property, boolean def)
737   {
738     String string = getProperty(property);
739     if (string != null)
740     {
741       def = Boolean.valueOf(string).booleanValue();
742     }
743
744     return def;
745   }
746
747   public static int getDefault(String property, int def)
748   {
749     String string = getProperty(property);
750     if (string != null)
751     {
752       try
753       {
754         def = Integer.parseInt(string);
755       } catch (NumberFormatException e)
756       {
757         System.out.println("Error parsing int property '" + property
758                 + "' with value '" + string + "'");
759       }
760     }
761
762     return def;
763   }
764
765   /**
766    * Answers the value of the given property, or the supplied default value if the
767    * property is not set
768    */
769   public static String getDefault(String property, String def)
770   {
771     String value = getProperty(property);
772     return value == null ? def : value;
773   }
774
775   /**
776    * Stores property in the file "HOME_DIR/.jalview_properties"
777    * 
778    * @param key
779    *              Name of object
780    * @param obj
781    *              String value of property
782    * 
783    * @return previous value of property (or null)
784    */
785   public static Object setProperty(String key, String obj)
786   {
787     Object oldValue = null;
788     try
789     {
790       oldValue = applicationProperties.setProperty(key, obj);
791       if (propertiesFile != null && !propsAreReadOnly)
792       {
793         FileOutputStream out = new FileOutputStream(propertiesFile);
794         applicationProperties.store(out, "---JalviewX Properties File---");
795         out.close();
796       }
797     } catch (Exception ex)
798     {
799       System.out.println(
800               "Error setting property: " + key + " " + obj + "\n" + ex);
801     }
802     return oldValue;
803   }
804
805   /**
806    * remove the specified property from the jalview properties file
807    * 
808    * @param string
809    */
810   public static void removeProperty(String string)
811   {
812     applicationProperties.remove(string);
813     saveProperties();
814   }
815
816   /**
817    * save the properties to the jalview properties path
818    */
819   public static void saveProperties()
820   {
821     if (!propsAreReadOnly)
822     {
823       try
824       {
825         FileOutputStream out = new FileOutputStream(propertiesFile);
826         applicationProperties.store(out, "---JalviewX Properties File---");
827         out.close();
828       } catch (Exception ex)
829       {
830         System.out.println("Error saving properties: " + ex);
831       }
832     }
833   }
834
835   /**
836    * internal vamsas class discovery state
837    */
838   private static int vamsasJarsArePresent = -1;
839
840   /**
841    * Searches for vamsas client classes on class path.
842    * 
843    * @return true if vamsas client is present on classpath
844    */
845   public static boolean vamsasJarsPresent()
846   {
847     if (vamsasJarsArePresent == -1)
848     {
849       try
850       {
851         if (jalview.jbgui.GDesktop.class.getClassLoader()
852                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
853         {
854           jalview.bin.Cache.log.debug(
855                   "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
856           vamsasJarsArePresent = 1;
857           Logger lvclient = Logger.getLogger("uk.ac.vamsas");
858           lvclient.setLevel(Level.toLevel(Cache
859                   .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
860
861           lvclient.addAppender(log.getAppender("JalviewLogger"));
862           // Tell the user that debug is enabled
863           lvclient.debug(ChannelProperties.getProperty("app_name")
864                   + " Vamsas Client Debugging Output Follows.");
865         }
866       } catch (Exception e)
867       {
868         vamsasJarsArePresent = 0;
869         jalview.bin.Cache.log.debug("Vamsas Classes are not present");
870       }
871     }
872     return (vamsasJarsArePresent > 0);
873   }
874
875   /**
876    * internal vamsas class discovery state
877    */
878   private static int groovyJarsArePresent = -1;
879
880   /**
881    * Searches for vamsas client classes on class path.
882    * 
883    * @return true if vamsas client is present on classpath
884    */
885   public static boolean groovyJarsPresent()
886   {
887     if (groovyJarsArePresent == -1)
888     {
889       try
890       {
891         if (Cache.class.getClassLoader()
892                 .loadClass("groovy.lang.GroovyObject") != null)
893         {
894           jalview.bin.Cache.log.debug(
895                   "Found Groovy (groovy.lang.GroovyObject can be loaded)");
896           groovyJarsArePresent = 1;
897           Logger lgclient = Logger.getLogger("groovy");
898           lgclient.setLevel(Level.toLevel(Cache
899                   .getDefault("logs.Groovy.Level", Level.INFO.toString())));
900
901           lgclient.addAppender(log.getAppender("JalviewLogger"));
902           // Tell the user that debug is enabled
903           lgclient.debug(ChannelProperties.getProperty("app_name")
904                   + " Groovy Client Debugging Output Follows.");
905         }
906       } catch (Error e)
907       {
908         groovyJarsArePresent = 0;
909         jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
910       } catch (Exception e)
911       {
912         groovyJarsArePresent = 0;
913         jalview.bin.Cache.log.debug("Groovy Classes are not present");
914       }
915     }
916     return (groovyJarsArePresent > 0);
917   }
918
919   /**
920    * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
921    * enabled.
922    */
923   protected static Object tracker = null;
924
925   protected static Class trackerfocus = null;
926
927   protected static Class jgoogleanalyticstracker = null;
928
929   /**
930    * Initialise the google tracker if it is not done already.
931    */
932   public static void initGoogleTracker()
933   {
934     if (tracker == null)
935     {
936       if (jgoogleanalyticstracker == null)
937       {
938         // try to get the tracker class
939         try
940         {
941           jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
942                   "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
943           trackerfocus = Cache.class.getClassLoader()
944                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
945         } catch (Exception e)
946         {
947           log.debug(
948                   "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
949           tracker = null;
950           jgoogleanalyticstracker = null;
951           trackerfocus = null;
952           return;
953         }
954       }
955       // now initialise tracker
956       Exception re = null, ex = null;
957       Error err = null;
958       String vrs = "No Version Accessible";
959       try
960       {
961         // Google analytics tracking code for Library Finder
962         tracker = jgoogleanalyticstracker
963                 .getConstructor(new Class[]
964                 { String.class, String.class, String.class })
965                 .newInstance(new Object[]
966                 { ChannelProperties.getProperty("app_name") + " Desktop",
967                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
968                             + jalview.bin.Cache.getDefault("BUILD_DATE",
969                                     "unknown")),
970                     "UA-9060947-1" });
971         jgoogleanalyticstracker
972                 .getMethod("trackAsynchronously", new Class[]
973                 { trackerfocus })
974                 .invoke(tracker, new Object[]
975                 { trackerfocus.getConstructor(new Class[] { String.class })
976                         .newInstance(new Object[]
977                         { "Application Started." }) });
978       } catch (RuntimeException e)
979       {
980         re = e;
981       } catch (Exception e)
982       {
983         ex = e;
984       } catch (Error e)
985       {
986         err = e;
987       }
988       if (re != null || ex != null || err != null)
989       {
990         if (log != null)
991         {
992           if (re != null)
993           {
994             log.debug("Caught runtime exception in googletracker init:",
995                     re);
996           }
997           if (ex != null)
998           {
999             log.warn(
1000                     "Failed to initialise GoogleTracker for Jalview Desktop with version "
1001                             + vrs,
1002                     ex);
1003           }
1004           if (err != null)
1005           {
1006             log.error(
1007                     "Whilst initing GoogleTracker for Jalview Desktop version "
1008                             + vrs,
1009                     err);
1010           }
1011         }
1012         else
1013         {
1014           if (re != null)
1015           {
1016             System.err.println(
1017                     "Debug: Caught runtime exception in googletracker init:"
1018                             + vrs);
1019             re.printStackTrace();
1020           }
1021           if (ex != null)
1022           {
1023             System.err.println(
1024                     "Warning:  Failed to initialise GoogleTracker for Jalview Desktop with version "
1025                             + vrs);
1026             ex.printStackTrace();
1027           }
1028
1029           if (err != null)
1030           {
1031             System.err.println(
1032                     "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
1033                             + vrs);
1034             err.printStackTrace();
1035           }
1036         }
1037       }
1038       else
1039       {
1040         log.debug("Successfully initialised tracker.");
1041       }
1042     }
1043   }
1044
1045   /**
1046    * get the user's default colour if available
1047    * 
1048    * @param property
1049    * @param defcolour
1050    * @return
1051    */
1052   public static Color getDefaultColour(String property, Color defcolour)
1053   {
1054     String colprop = getProperty(property);
1055     if (colprop == null)
1056     {
1057       return defcolour;
1058     }
1059     Color col = ColorUtils.parseColourString(colprop);
1060     if (col == null)
1061     {
1062       log.warn("Couldn't parse '" + colprop + "' as a colour for "
1063               + property);
1064     }
1065     return (col == null) ? defcolour : col;
1066   }
1067
1068   /**
1069    * store a colour as a Jalview user default property
1070    * 
1071    * @param property
1072    * @param colour
1073    */
1074   public static void setColourProperty(String property, Color colour)
1075   {
1076     setProperty(property, jalview.util.Format.getHexString(colour));
1077   }
1078
1079   /**
1080    * Stores a formatted date in a jalview property, using a fixed locale.
1081    * 
1082    * @param propertyName
1083    * @param date
1084    * @return the formatted date string
1085    */
1086   public static String setDateProperty(String propertyName, Date date)
1087   {
1088     String formatted = date_format.format(date);
1089     setProperty(propertyName, formatted);
1090     return formatted;
1091   }
1092
1093   /**
1094    * Reads a date stored in a Jalview property, parses it (using a fixed locale
1095    * format) and returns as a Date, or null if parsing fails
1096    * 
1097    * @param propertyName
1098    * @return
1099    * 
1100    */
1101   public static Date getDateProperty(String propertyName)
1102   {
1103     String val = getProperty(propertyName);
1104     if (val != null)
1105     {
1106       try
1107       {
1108         return date_format.parse(val);
1109       } catch (Exception ex)
1110       {
1111         System.err.println("Invalid or corrupt date in property '"
1112                 + propertyName + "' : value was '" + val + "'");
1113       }
1114     }
1115     return null;
1116   }
1117
1118   /**
1119    * get and parse a property as an integer. send any parsing problems to
1120    * System.err
1121    * 
1122    * @param property
1123    * @return null or Integer
1124    */
1125   public static Integer getIntegerProperty(String property)
1126   {
1127     String val = getProperty(property);
1128     if (val != null && (val = val.trim()).length() > 0)
1129     {
1130       try
1131       {
1132         return Integer.valueOf(val);
1133       } catch (NumberFormatException x)
1134       {
1135         System.err.println("Invalid integer in property '" + property
1136                 + "' (value was '" + val + "')");
1137       }
1138     }
1139     return null;
1140   }
1141
1142   /**
1143    * Set the specified value, or remove it if null or empty. Does not save the
1144    * properties file.
1145    * 
1146    * @param propName
1147    * @param value
1148    */
1149   public static void setOrRemove(String propName, String value)
1150   {
1151     if (propName == null)
1152     {
1153       return;
1154     }
1155     if (value == null || value.trim().length() < 1)
1156     {
1157       Cache.applicationProperties.remove(propName);
1158     }
1159     else
1160     {
1161       Cache.applicationProperties.setProperty(propName, value);
1162     }
1163   }
1164
1165   /**
1166    * Loads in user colour schemes from files.
1167    * 
1168    * @param files
1169    *                a '|'-delimited list of file paths
1170    */
1171   public static void initUserColourSchemes(String files)
1172   {
1173     if (files == null || files.length() == 0)
1174     {
1175       return;
1176     }
1177
1178     // In case colours can't be loaded, we'll remove them
1179     // from the default list here.
1180     StringBuffer coloursFound = new StringBuffer();
1181     StringTokenizer st = new StringTokenizer(files, "|");
1182     while (st.hasMoreElements())
1183     {
1184       String file = st.nextToken();
1185       try
1186       {
1187         UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1188         if (ucs != null)
1189         {
1190           if (coloursFound.length() > 0)
1191           {
1192             coloursFound.append("|");
1193           }
1194           coloursFound.append(file);
1195           ColourSchemes.getInstance().registerColourScheme(ucs);
1196         }
1197       } catch (Exception ex)
1198       {
1199         System.out.println("Error loading User ColourFile\n" + ex);
1200       }
1201     }
1202     if (!files.equals(coloursFound.toString()))
1203     {
1204       if (coloursFound.toString().length() > 1)
1205       {
1206         setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1207                 coloursFound.toString());
1208       }
1209       else
1210       {
1211         applicationProperties
1212                 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1213       }
1214     }
1215   }
1216
1217   /**
1218    * Initial logging information helper for various versions output
1219    * 
1220    * @param prefix
1221    * @param value
1222    * @param defaultValue
1223    */
1224   private static void appendIfNotNull(StringBuilder sb, String prefix,
1225           String value, String suffix, String defaultValue)
1226   {
1227     if (value == null && defaultValue == null)
1228     {
1229       return;
1230     }
1231     String line = prefix + (value != null ? value : defaultValue) + suffix;
1232     sb.append(line);
1233   }
1234
1235   /**
1236    * 
1237    * @return Jalview version, build details and JVM platform version for console
1238    */
1239   public static String getVersionDetailsForConsole()
1240   {
1241     StringBuilder sb = new StringBuilder();
1242     sb.append(ChannelProperties.getProperty("app_name"))
1243             .append(" Version: ");
1244     sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1245     sb.append("\n");
1246     sb.append(ChannelProperties.getProperty("app_name"))
1247             .append(" Installation: ");
1248     sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1249     sb.append("\n");
1250     sb.append("Build Date: ");
1251     sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1252     sb.append("\n");
1253     sb.append("Java version: ");
1254     sb.append(System.getProperty("java.version"));
1255     sb.append("\n");
1256     sb.append(System.getProperty("os.arch"));
1257     sb.append(" ");
1258     sb.append(System.getProperty("os.name"));
1259     sb.append(" ");
1260     sb.append(System.getProperty("os.version"));
1261     sb.append("\n");
1262     appendIfNotNull(sb, "Install4j version: ",
1263             System.getProperty("sys.install4jVersion"), "\n", null);
1264     appendIfNotNull(sb, "Install4j template version: ",
1265             System.getProperty("installer_template_version"), "\n", null);
1266     appendIfNotNull(sb, "Launcher version: ",
1267             System.getProperty("launcher_version"), "\n", null);
1268     LookAndFeel laf = UIManager.getLookAndFeel();
1269     String lafName = laf == null ? "Not obtained" : laf.getName();
1270     String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1271     sb.append("LookAndFeel: ");
1272     sb.append(lafName);
1273     sb.append(" (");
1274     sb.append(lafClass);
1275     sb.append(")\n");
1276     // Not displayed in release version ( determined by possible version number
1277     // regex 9[9.]*9[.-_a9]* )
1278     if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1279             jalview.bin.Cache.getDefault("VERSION", "TEST")))
1280     {
1281       appendIfNotNull(sb, "Getdown appdir: ",
1282               System.getProperty("getdownappdir"), "\n", null);
1283       appendIfNotNull(sb, "Getdown appbase: ",
1284               System.getProperty("getdownappbase"), "\n", null);
1285       appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1286               "\n", "unknown");
1287     }
1288     return sb.toString();
1289   }
1290
1291   /**
1292    * 
1293    * @return build details as reported in splashscreen
1294    */
1295   public static String getBuildDetailsForSplash()
1296   {
1297     // consider returning more human friendly info
1298     // eg 'built from Source' or update channel
1299     return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1300   }
1301
1302   public static String getStackTraceString(Throwable t)
1303   {
1304     StringWriter sw = new StringWriter();
1305     PrintWriter pw = new PrintWriter(sw);
1306     t.printStackTrace(pw);
1307     return sw.toString();
1308   }
1309
1310   // proxy properties methods
1311   public static void clearProxyProperties()
1312   {
1313     setProxyProperties(null, null, null, null, null, null, null, null,
1314             null);
1315   }
1316
1317   public static void resetProxyProperties()
1318   {
1319     setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1320             startupProxyProperties[2], startupProxyProperties[3],
1321             startupProxyProperties[4],
1322             startupProxyProperties[5] == null ? null
1323                     : startupProxyProperties[5].toCharArray(),
1324             startupProxyProperties[6],
1325             startupProxyProperties[7] == null ? null
1326                     : startupProxyProperties[7].toCharArray(),
1327             startupProxyProperties[8]);
1328     StringBuilder sb = new StringBuilder();
1329     sb.append("Setting proxy properties to: http.proxyHost=")
1330             .append(startupProxyProperties[0]).append(", http.proxyPort=")
1331             .append(startupProxyProperties[1])
1332             .append(startupProxyProperties[4] != null
1333                     && !startupProxyProperties[4].isEmpty()
1334                             ? " [" + startupProxyProperties[4] + "]"
1335                             : "")
1336             .append(", https.proxyHost=").append(startupProxyProperties[2])
1337             .append(", https.proxyPort=").append(startupProxyProperties[3])
1338             .append(startupProxyProperties[6] != null
1339                     && !startupProxyProperties[6].isEmpty()
1340                             ? " [" + startupProxyProperties[6] + "]"
1341                             : "");
1342
1343     Cache.debug(sb.toString());
1344   }
1345
1346   public static void setProxyPropertiesFromPreferences()
1347   {
1348     setProxyPropertiesFromPreferences(Cache.PROXYTYPE_SYSTEM);
1349   }
1350
1351   public static void setProxyPropertiesFromPreferences(
1352           String previousProxyType)
1353   {
1354     String proxyType = Cache.getDefault("USE_PROXY",
1355             Cache.PROXYTYPE_SYSTEM);
1356     if (previousProxyType != null
1357             && !proxyType.equals(Cache.PROXYTYPE_CUSTOM) // always apply
1358                                                          // customProxy
1359             && proxyType.equals(previousProxyType))
1360     {
1361       // no change
1362       return;
1363     }
1364     switch (proxyType)
1365     {
1366     case Cache.PROXYTYPE_NONE:
1367       if (!previousProxyType.equals(proxyType))
1368       {
1369         Cache.log.info("Setting no proxy settings");
1370         Cache.setProxyProperties(null, null, null, null, null, null, null,
1371                 null, null);
1372       }
1373       break;
1374     case Cache.PROXYTYPE_CUSTOM:
1375       // always re-set a custom proxy -- it might have changed, particularly
1376       // password
1377       Cache.log.info("Setting custom proxy settings");
1378       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
1379       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
1380               Cache.getDefault("PROXY_PORT", null),
1381               Cache.getDefault("PROXY_SERVER_HTTPS", null),
1382               Cache.getDefault("PROXY_PORT_HTTPS", null),
1383               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1384                       : null,
1385               proxyAuthSet ? Cache.proxyAuthPassword : null,
1386               proxyAuthSet ? Cache.getDefault("PROXY_AUTH_USERNAME", "")
1387                       : null,
1388               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
1389       break;
1390     default: // system proxy settings by default
1391       Cache.log.info("Setting system proxy settings");
1392       Cache.resetProxyProperties();
1393     }
1394   }
1395
1396   public static void setProxyProperties(String httpHost, String httpPort,
1397           String httpsHost, String httpsPort, String httpUser,
1398           char[] httpPassword, String httpsUser, char[] httpsPassword,
1399           String nonProxyHosts)
1400   {
1401     setOrClearSystemProperty("http.proxyHost", httpHost);
1402     setOrClearSystemProperty("http.proxyPort", httpPort);
1403     setOrClearSystemProperty("https.proxyHost", httpsHost);
1404     setOrClearSystemProperty("https.proxyPort", httpsPort);
1405     setOrClearSystemProperty("http.proxyUser", httpUser);
1406     setOrClearSystemProperty("https.proxyUser", httpsUser);
1407     // note: passwords for http.proxyPassword and https.proxyPassword are sent
1408     // via the Authenticator, properties do not need to be set
1409
1410     // are we using a custom proxy (password prompt might be required)?
1411     boolean customProxySet = getDefault("USE_PROXY", PROXYTYPE_SYSTEM)
1412             .equals(PROXYTYPE_CUSTOM);
1413
1414     /*
1415      * A bug in Java means the AuthCache does not get reset, so once it has working credentials,
1416      * it never asks for more, so changing the Authenticator has no effect (as getPasswordAuthentication()
1417      * is not re-called).
1418      * This could lead to password leak to a hostile proxy server, so I'm putting in a hack to clear
1419      * the AuthCache.
1420      * see https://www.generacodice.com/en/articolo/154918/Reset-the-Authenticator-credentials
1421      * ...
1422      * Turns out this is only accessible in Java 8, and not in Java 9 onwards, so commenting out
1423      */
1424     /*
1425     try
1426     {
1427       sun.net.www.protocol.http.AuthCacheValue
1428               .setAuthCache(new sun.net.www.protocol.http.AuthCacheImpl());
1429     } catch (Throwable t)
1430     {
1431       Cache.error(t.getMessage());
1432       Cache.debug(getStackTraceString(t));
1433     }
1434     */
1435
1436     if (httpUser != null || httpsUser != null)
1437     {
1438       try
1439       {
1440         char[] displayHttpPw = new char[httpPassword == null ? 0
1441                 : httpPassword.length];
1442         Arrays.fill(displayHttpPw, '*');
1443         Cache.debug("CACHE Proxy: setting new Authenticator with httpUser='"
1444                 + httpUser + "' httpPassword='" + displayHttpPw + "'");
1445         if (!Platform.isJS())
1446         /* *
1447          * java.net.Authenticator not implemented in SwingJS yet
1448          * 
1449          * @j2sIgnore
1450          * 
1451          */
1452         {
1453           Authenticator.setDefault(new Authenticator()
1454           {
1455             @Override
1456             protected PasswordAuthentication getPasswordAuthentication()
1457             {
1458               if (getRequestorType() == RequestorType.PROXY)
1459               {
1460                 String protocol = getRequestingProtocol();
1461                 boolean needProxyPasswordSet = false;
1462                 if (customProxySet &&
1463                 // we have a username but no password for the scheme being
1464                 // requested
1465                 (protocol.equalsIgnoreCase("http")
1466                         && (httpUser != null && httpUser.length() > 0
1467                                 && (httpPassword == null
1468                                         || httpPassword.length == 0)))
1469                         || (protocol.equalsIgnoreCase("https")
1470                                 && (httpsUser != null
1471                                         && httpsUser.length() > 0
1472                                         && (httpsPassword == null
1473                                                 || httpsPassword.length == 0))))
1474                 {
1475                   // open Preferences -> Connections
1476                   String message = MessageManager
1477                           .getString("label.proxy_password_required");
1478                   Preferences.openPreferences(
1479                           Preferences.TabRef.CONNECTIONS_TAB, message);
1480                   Preferences.getInstance()
1481                           .proxyAuthPasswordCheckHighlight(true, true);
1482                 }
1483                 else
1484                 {
1485                   try
1486                   {
1487                     if (protocol.equalsIgnoreCase("http")
1488                             && getRequestingHost()
1489                                     .equalsIgnoreCase(httpHost)
1490                             && getRequestingPort() == Integer
1491                                     .valueOf(httpPort))
1492                     {
1493                       Cache.debug(
1494                               "AUTHENTICATOR returning PasswordAuthentication(\""
1495                                       + httpUser + "\", '"
1496                                       + new String(displayHttpPw) + "')");
1497                       return new PasswordAuthentication(httpUser,
1498                               httpPassword);
1499                     }
1500                     if (protocol.equalsIgnoreCase("https")
1501                             && getRequestingHost()
1502                                     .equalsIgnoreCase(httpsHost)
1503                             && getRequestingPort() == Integer
1504                                     .valueOf(httpsPort))
1505                     {
1506                       char[] displayHttpsPw = new char[httpPassword.length];
1507                       Arrays.fill(displayHttpsPw, '*');
1508                       Cache.debug(
1509                               "AUTHENTICATOR returning PasswordAuthentication(\""
1510                                       + httpsUser + "\", '" + displayHttpsPw
1511                                       + "'");
1512                       return new PasswordAuthentication(httpsUser,
1513                               httpsPassword);
1514                     }
1515                   } catch (NumberFormatException e)
1516                   {
1517                     Cache.error("Problem with proxy port values [http:"
1518                             + httpPort + ", https:" + httpsPort + "]");
1519                   }
1520                   Cache.debug(
1521                           "AUTHENTICATOR after trying to get PasswordAuthentication");
1522                 }
1523               }
1524               // non proxy request
1525               Cache.debug("AUTHENTICATOR returning null");
1526               return null;
1527             }
1528           });
1529         } // end of j2sIgnore for java.net.Authenticator
1530
1531         // required to re-enable basic authentication (should be okay for a
1532         // local proxy)
1533         Cache.debug(
1534                 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
1535         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1536       } catch (SecurityException e)
1537       {
1538         Cache.error("Could not set default Authenticator");
1539         Cache.debug(getStackTraceString(e));
1540       }
1541     }
1542     else
1543     {
1544       // reset the Authenticator to protect http.proxyUser and
1545       // http.proxyPassword Just In Case
1546       /* as noted above, due to bug in java this doesn't work if the sun.net.www.protocol.http.AuthCache
1547        * has working credentials. No workaround for Java 11.
1548        */
1549       if (!Platform.isJS())
1550       /* *
1551        * java.net.Authenticator not implemented in SwingJS yet
1552        * 
1553        * @j2sIgnore
1554        * 
1555        */
1556       {
1557         Cache.debug("AUTHENTICATOR setting default Authenticator to null");
1558         Authenticator.setDefault(null);
1559       }
1560     }
1561
1562     // nonProxyHosts not currently configurable in Preferences
1563     Cache.debug("AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
1564             + nonProxyHosts + "\"");
1565     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
1566   }
1567
1568   public static void setOrClearSystemProperty(String key, char[] value)
1569   {
1570     setOrClearSystemProperty(key,
1571             (value == null) ? null : new String(value));
1572   }
1573
1574   public static void setOrClearSystemProperty(String key, String value)
1575   {
1576     if (key == null)
1577     {
1578       return;
1579     }
1580     if (value == null)
1581     {
1582       System.clearProperty(key);
1583     }
1584     else
1585     {
1586       System.setProperty(key, value);
1587     }
1588   }
1589
1590   public final static int TRACE = 10;
1591
1592   public final static int DEBUG = 20;
1593
1594   public final static int INFO = 30;
1595
1596   public final static int WARN = 40;
1597
1598   public final static int ERROR = 50;
1599
1600   public static boolean println(int level, String message)
1601   {
1602     if (Cache.log == null)
1603     {
1604       if (level >= WARN)
1605         System.err.println(message);
1606       else if (level >= INFO)
1607         System.out.println(message);
1608       // not printing debug or trace messages
1609       return false;
1610     }
1611     if (level >= ERROR)
1612     {
1613       Cache.log.error(message);
1614     }
1615     else if (level >= WARN)
1616     {
1617       Cache.log.warn(message);
1618     }
1619     else if (level >= INFO)
1620     {
1621       Cache.log.info(message);
1622     }
1623     else if (level >= DEBUG)
1624     {
1625       Cache.log.debug(message);
1626     }
1627     else
1628     {
1629       Cache.log.trace(message);
1630     }
1631     return true;
1632   }
1633
1634   public static void trace(String message)
1635   {
1636     println(TRACE, message);
1637   }
1638
1639   public static void debug(String message)
1640   {
1641     println(DEBUG, message);
1642   }
1643
1644   public static void info(String message)
1645   {
1646     println(INFO, message);
1647   }
1648
1649   public static void warn(String message)
1650   {
1651     println(WARN, message);
1652   }
1653
1654   public static void error(String message)
1655   {
1656     println(ERROR, message);
1657   }
1658
1659   /**
1660    * Getdown appbase methods
1661    */
1662
1663   private static final String releaseAppbase;
1664
1665   private static String getdownAppbase;
1666
1667   private static String getdownDistDir;
1668
1669   static
1670   {
1671     if (!Platform.isJS())
1672     {
1673       Float specversion = Float
1674               .parseFloat(System.getProperty("java.specification.version"));
1675       releaseAppbase = (specversion < 9)
1676               ? "https://www.jalview.org/getdown/release/1.8"
1677               : "https://www.jalview.org/getdown/release/11";
1678     }
1679     else
1680     {
1681       // this value currenly made up, can be changed to URL that will be
1682       // "https://www.jalview.org/jalview-js/swingjs/j2s/build_properties"
1683       releaseAppbase = "https://www.jalview.org/jalview-js";
1684       getdownAppbase = releaseAppbase;
1685       getdownDistDir = "/swingjs/j2s";
1686     }
1687   }
1688
1689   // look for properties (passed in by getdown) otherwise default to release
1690   private static void setGetdownAppbase()
1691   {
1692     if (getdownAppbase != null)
1693     {
1694       return;
1695     }
1696     String appbase = System.getProperty("getdownappbase");
1697     String distDir = System.getProperty("getdowndistdir");
1698     if (appbase == null)
1699     {
1700       appbase = buildProperties.getProperty("GETDOWNAPPBASE");
1701       distDir = buildProperties.getProperty("GETDOWNAPPDISTDIR");
1702     }
1703     if (appbase == null)
1704     {
1705       appbase = releaseAppbase;
1706       distDir = "release";
1707     }
1708     if (appbase.endsWith("/"))
1709     {
1710       appbase = appbase.substring(0, appbase.length() - 1);
1711     }
1712     if (distDir == null)
1713     {
1714       distDir = appbase.equals(releaseAppbase) ? "release" : "alt";
1715     }
1716     getdownAppbase = appbase;
1717     getdownDistDir = distDir;
1718   }
1719
1720   public static String getGetdownAppbase()
1721   {
1722     setGetdownAppbase();
1723     return getdownAppbase;
1724   }
1725
1726   public static String getAppbaseBuildProperties()
1727   {
1728     String appbase = getGetdownAppbase();
1729     return appbase + "/" + getdownDistDir + "/build_properties";
1730   }
1731 }