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