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