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