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