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