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