2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import java.awt.Color;
24 import java.io.BufferedReader;
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;
35 import java.text.DateFormat;
36 import java.text.SimpleDateFormat;
37 import java.util.Collections;
38 import java.util.Date;
39 import java.util.Enumeration;
40 import java.util.Locale;
41 import java.util.Properties;
42 import java.util.StringTokenizer;
43 import java.util.TreeSet;
44 import java.util.regex.Pattern;
46 import javax.swing.LookAndFeel;
47 import javax.swing.UIManager;
49 import org.apache.log4j.ConsoleAppender;
50 import org.apache.log4j.Level;
51 import org.apache.log4j.Logger;
52 import org.apache.log4j.SimpleLayout;
54 import jalview.datamodel.PDBEntry;
55 import jalview.gui.UserDefinedColours;
56 import jalview.schemes.ColourSchemeLoader;
57 import jalview.schemes.ColourSchemes;
58 import jalview.schemes.UserColourScheme;
59 import jalview.structure.StructureImportSettings;
60 import jalview.urls.IdOrgSettings;
61 import jalview.util.ColorUtils;
62 import jalview.util.Platform;
63 import jalview.ws.sifts.SiftsSettings;
66 * Stores and retrieves Jalview Application Properties Lists and fields within
67 * list entries are separated by '|' symbols unless otherwise stated (|) clauses
68 * are alternative values for a tag. <br>
70 * Current properties include:
73 * logs.Axis.Level - one of the stringified Levels for log4j controlling the
74 * logging level for axis (used for web services) <br>
76 * <li>logs.Castor.Level - one of the stringified Levels for log4j controlling
77 * the logging level for castor (used for serialization) <br>
79 * <li>logs.Jalview.Level - Cache.log stringified level. <br>
81 * <li>SCREEN_WIDTH</li>
82 * <li>SCREEN_HEIGHT</li>
83 * <li>SCREEN_Y=285</li>
84 * <li>SCREEN_X=371</li>
85 * <li>SHOW_FULLSCREEN boolean</li>
86 * <li>FONT_NAME java font name for alignment text display</li>
87 * <li>FONT_SIZE size of displayed alignment text</li>
88 * <li>FONT_STYLE style of font displayed (sequence labels are always
90 * <li>GAP_SYMBOL character to treat as gap symbol (usually -,.,' ')</li>
91 * <li>LAST_DIRECTORY last directory for browsing alignment</li>
92 * <li>USER_DEFINED_COLOURS list of user defined colour scheme files</li>
93 * <li>SHOW_FULL_ID show id with '/start-end' numbers appended</li>
94 * <li>SHOW_IDENTITY show percentage identity annotation</li>
95 * <li>SHOW_QUALITY show alignment quality annotation</li>
96 * <li>SHOW_ANNOTATIONS show alignment annotation rows</li>
97 * <li>SHOW_CONSERVATION show alignment conservation annotation</li>
98 * <li>SORT_ANNOTATIONS currently either SEQUENCE_AND_LABEL or
99 * LABEL_AND_SEQUENCE</li>
100 * <li>SHOW_AUTOCALC_ABOVE true to show autocalculated annotations above
101 * sequence annotations</li>
102 * <li>CENTRE_COLUMN_LABELS centre the labels at each column in a displayed
103 * annotation row</li>
104 * <li>DEFAULT_COLOUR default colour scheme to apply for a new alignment</li>
105 * <li>DEFAULT_FILE_FORMAT file format used to save</li>
106 * <li>STARTUP_FILE file loaded on startup (may be a fully qualified url)</li>
107 * <li>SHOW_STARTUP_FILE flag to control loading of startup file</li>
108 * <li>VERSION the version of the jalview build</li>
109 * <li>BUILD_DATE date of this build</li>
110 * <li>LATEST_VERSION the latest jalview version advertised on the
111 * www.jalview.org</li>
112 * <li>PIR_MODELLER boolean indicating if PIR files are written with MODELLER
114 * <li>(FASTA,MSF,PILEUP,CLUSTAL,BLC,PIR,PFAM)_JVSUFFIX boolean for adding jv
115 * suffix to file</li>
116 * <li>RECENT_URL list of recently retrieved URLs</li>
117 * <li>RECENT_FILE list of recently opened files</li>
118 * <li>USE_PROXY flag for whether a http proxy is to be used</li>
119 * <li>PROXY_SERVER the proxy</li>
120 * <li>PROXY_PORT</li>
121 * <li>NOQUESTIONNAIRES true to prevent jalview from checking the questionnaire
123 * <li>QUESTIONNAIRE last questionnaire:responder id string from questionnaire
125 * <li>USAGESTATS (false - user prompted) Enable google analytics tracker for
126 * collecting usage statistics</li>
127 * <li>SHOW_OVERVIEW boolean for overview window display</li>
128 * <li>ANTI_ALIAS boolean for smooth fonts</li>
129 * <li>RIGHT_ALIGN_IDS boolean</li>
130 * <li>AUTO_CALC_CONSENSUS boolean for automatic recalculation of consensus</li>
131 * <li>PAD_GAPS boolean</li>
132 * <li>ID_ITALICS boolean</li>
133 * <li>SHOW_JV_SUFFIX</li>
134 * <li>WRAP_ALIGNMENT</li>
135 * <li>EPS_RENDERING (Prompt each time|Lineart|Text) default for EPS rendering
137 * <li>SORT_ALIGNMENT (No sort|Id|Pairwise Identity)</li>
138 * <li>SEQUENCE_LINKS list of name|URL pairs for opening a url with
140 * <li>STORED_LINKS list of name|url pairs which user has entered but are not
142 * <li>DEFAULT_LINK name of single url to be used when user double clicks a
143 * sequence id (must be in SEQUENCE_LINKS or STORED_LINKS)
144 * <li>GROUP_LINKS list of name|URL[|<separator>] tuples - see
145 * jalview.utils.GroupURLLink for more info</li>
146 * <li>DEFAULT_BROWSER for unix</li>
147 * <li>SHOW_MEMUSAGE boolean show memory usage and warning indicator on desktop
149 * <li>VERSION_CHECK (true) check for the latest release version from
150 * www.jalview.org (or the alias given by the www.jalview.org property)</li>
151 * <li>SHOW_NPFEATS_TOOLTIP (true) show non-positional features in the Sequence
153 * <li>SHOW_DBREFS_TOOLTIP (true) show Database Cross References in the Sequence
155 * <li>SHOW_UNCONSERVED (false) only render unconserved residues - conserved
156 * displayed as '.'</li>
157 * <li>SORT_BY_TREE (false) sort the current alignment view according to the
158 * order of a newly displayed tree</li>
159 * <li>DBFETCH_USEPICR (false) use PICR to recover valid DB references from
160 * sequence ID strings before attempting retrieval from any datasource</li>
161 * <li>SHOW_GROUP_CONSENSUS (false) Show consensus annotation for groups in the
163 * <li>SHOW_GROUP_CONSERVATION (false) Show conservation annotation for groups
164 * in the alignment.</li>
165 * <li>SHOW_CONSENSUS_HISTOGRAM (false) Show consensus annotation row's
167 * <li>SHOW_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
169 * <li>NORMALISE_CONSENSUS_LOGO (false) Show consensus annotation row's sequence
170 * logo normalised to row height rather than histogram height.</li>
171 * <li>FOLLOW_SELECTIONS (true) Controls whether a new alignment view should
172 * respond to selections made in other alignments containing the same sequences.
174 * <li>JWS2HOSTURLS comma-separated list of URLs to try for JABAWS services</li>
175 * <li>SHOW_WSDISCOVERY_ERRORS (true) Controls if the web service URL discovery
176 * warning dialog box is displayed.</li>
177 * <li>ANNOTATIONCOLOUR_MIN (orange) Shade used for minimum value of annotation
178 * when shading by annotation</li>
179 * <li>ANNOTATIONCOLOUR_MAX (red) Shade used for maximum value of annotation
180 * when shading by annotation</li>
181 * <li>www.jalview.org (http://www.jalview.org) a property enabling all HTTP
182 * requests to be redirected to a mirror of http://www.jalview.org</li>
183 * <li>FIGURE_AUTOIDWIDTH (false) Expand the left hand column of an exported
184 * alignment figure to accommodate even the longest sequence ID or annotation
186 * <li>FIGURE_FIXEDIDWIDTH Specifies the width to use for the left-hand column
187 * when exporting an alignment as a figure (setting FIGURE_AUTOIDWIDTH to true
188 * will override this).</li>
189 * <li>STRUCT_FROM_PDB (false) derive secondary structure annotation from PDB
191 * <li>USE_RNAVIEW (false) use RNAViewer to derive secondary structure</li>
192 * <li>ADD_SS_ANN (false) add secondary structure annotation to alignment
194 * <li>ADD_TEMPFACT_ANN (false) add Temperature Factor annotation to alignment
196 * <li>STRUCTURE_DISPLAY choose from JMOL (default) or CHIMERA for 3D structure
198 * <li>CHIMERA_PATH specify full path to Chimera program (if non-standard)</li>
199 * <li>ID_ORG_HOSTURL location of jalview service providing identifiers.org urls
203 * Deprecated settings:
206 * <li>DISCOVERY_START - Boolean - controls if discovery services are queried on
207 * startup (JWS1 services only)</li>
208 * <li>DISCOVERY_URLS - comma separated list of Discovery Service endpoints.
209 * (JWS1 services only)</li>
210 * <li>SHOW_JWS1_SERVICES (true) enable or disable the original Jalview 2
211 * services in the desktop GUI</li>
212 * <li>ENABLE_RSBS_EDITOR (false for 2.7 release) enable or disable RSBS editing
213 * panel in web service preferences</li>
217 * @version $Revision$
222 * property giving log4j level for CASTOR loggers
224 public static final String CASTORLOGLEVEL = "logs.Castor.level";
227 * property giving log4j level for AXIS loggers
229 public static final String AXISLOGLEVEL = "logs.Axis.level";
232 * property giving log4j level for Jalview Log
234 public static final String JALVIEWLOGLEVEL = "logs.Jalview.level";
239 public static final String DEFAULT_SIFTS_DOWNLOAD_DIR = System
240 .getProperty("user.home") + File.separatorChar
241 + ".sifts_downloads" + File.separatorChar;
243 private final static String DEFAULT_CACHE_THRESHOLD_IN_DAYS = "2";
245 private final static String DEFAULT_FAIL_SAFE_PID_THRESHOLD = "30";
248 * Identifiers.org download settings
250 private static final String ID_ORG_FILE = System.getProperty("user.home")
251 + File.separatorChar + ".identifiers.org.ids.json";
254 * Allowed values are PDB or mmCIF
256 private final static String PDB_DOWNLOAD_FORMAT = PDBEntry.Type.MMCIF
259 private final static String DEFAULT_PDB_FILE_PARSER = StructureImportSettings.StructureParser.JMOL_PARSER
263 * a date formatter using a fixed (rather than the user's) locale;
264 * this ensures that date properties can be written and re-read successfully
265 * even if the user changes their locale setting
267 private static final DateFormat date_format = SimpleDateFormat
268 .getDateTimeInstance(SimpleDateFormat.MEDIUM,
269 SimpleDateFormat.MEDIUM, Locale.UK);
272 * Initialises the Jalview Application Log
274 public static Logger log;
276 // save the proxy properties set at startup
277 public final static String[] startupProxyProperties = {
278 System.getProperty("http.proxyHost"),
279 System.getProperty("http.proxyPort"),
280 System.getProperty("https.proxyHost"),
281 System.getProperty("https.proxyPort"),
282 System.getProperty("http.proxyUser"),
283 System.getProperty("http.proxyPassword"),
284 System.getProperty("https.proxyUser"),
285 System.getProperty("https.proxyPassword"),
286 System.getProperty("http.nonProxyHosts") };
288 public final static String PROXYTYPE_NONE = "none";
290 // "false" and "true" for backward compatibility
291 public final static String PROXYTYPE_SYSTEM = "false";
293 public final static String PROXYTYPE_CUSTOM = "true";
295 /** Jalview Properties */
296 public static Properties applicationProperties = new Properties()
298 // override results in properties output in alphabetical order
300 public synchronized Enumeration<Object> keys()
302 return Collections.enumeration(new TreeSet<>(super.keySet()));
306 /** Default file is ~/.jalview_properties */
307 static String propertiesFile;
309 private static boolean propsAreReadOnly = Platform.isJS();
311 private final static String JS_PROPERTY_PREFIX = "jalview_";
313 public static void initLogger()
321 // TODO: redirect stdout and stderr here in order to grab the output of
324 ConsoleAppender ap = new ConsoleAppender(new SimpleLayout(),
326 ap.setName("JalviewLogger");
327 org.apache.log4j.Logger.getRootLogger().addAppender(ap); // catch all for
329 Logger laxis = Logger.getLogger("org.apache.axis");
330 Logger lcastor = Logger.getLogger("org.exolab.castor");
331 jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
333 laxis.setLevel(Level.toLevel(
334 Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
335 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
336 Level.INFO.toString())));
337 lcastor = Logger.getLogger("org.exolab.castor.xml");
338 lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
339 Level.INFO.toString())));
340 // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
341 // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
342 // Level.INFO.toString())));
343 // we shouldn't need to do this
344 org.apache.log4j.Logger.getRootLogger()
345 .setLevel(org.apache.log4j.Level.INFO);
347 jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
348 .getDefault("logs.Jalview.level", Level.INFO.toString())));
349 // laxis.addAppender(ap);
350 // lcastor.addAppender(ap);
351 // jalview.bin.Cache.log.addAppender(ap);
352 // Tell the user that debug is enabled
353 jalview.bin.Cache.log.debug("Jalview Debugging Output Follows.");
354 } catch (Exception ex)
356 System.err.println("Problems initializing the log4j system\n");
357 ex.printStackTrace(System.err);
362 * Loads properties from the given properties file. Any existing properties
365 public static void loadProperties(String propsFile)
367 propertiesFile = propsFile;
368 if (propsFile == null && !propsAreReadOnly)
370 propertiesFile = System.getProperty("user.home") + File.separatorChar
371 + ".jalview_properties";
375 // don't corrupt the file we've been given.
376 propsAreReadOnly = true;
379 if (propertiesFile == null)
381 Platform.readInfoProperties(JS_PROPERTY_PREFIX,
382 applicationProperties);
391 fis = new URL(propertiesFile).openStream();
393 "Loading jalview properties from : " + propertiesFile);
395 "Disabling Jalview writing to user's local properties file.");
396 propsAreReadOnly = true;
398 } catch (Exception ex)
404 fis = new FileInputStream(propertiesFile);
406 applicationProperties.clear();
407 applicationProperties.load(fis);
409 // remove any old build properties
411 deleteBuildProperties();
413 } catch (Exception ex)
415 System.out.println("Error reading properties file: " + ex);
419 /* TO BE REPLACED WITH PROXY_TYPE SETTINGS
420 if (getDefault("USE_PROXY", false))
422 String proxyServer = getDefault("PROXY_SERVER", ""),
423 proxyPort = getDefault("PROXY_PORT", "8080");
427 // PROXY TYPE settings (now three options "none", "false", "true", but using
428 // backward compatible strings)
429 String proxyType = getDefault("USE_PROXY", PROXYTYPE_SYSTEM);
430 // default to upgrading old settings
434 setProxyProperties(null, null, null, null, null, null, null, null);
436 case PROXYTYPE_SYSTEM: // use system settings
437 resetProxyProperties();
439 case PROXYTYPE_CUSTOM: // use specified proxy settings
440 String httpHost = getDefault("PROXY_SERVER", "");
441 String httpPort = getDefault("PROXY_PORT", "8080");
442 String httpsHost = getDefault("PROXY_SERVER_HTTPS", httpHost);
443 String httpsPort = getDefault("PROXY_PORT_HTTPS", httpPort);
444 String httpUser = getDefault("PROXY_AUTH_USER", null);
445 String httpPassword = getDefault("PROXY_AUTH_PASSWORD", null);
446 // https.proxyUser and https.proxyPassword are not able to be
447 // independently set in Preferences yet
448 String httpsUser = getDefault("PROXY_AUTH_USER_HTTPS", httpUser);
449 String httpsPassword = getDefault("PROXY_AUTH_PASSWORD_HTTPS",
451 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
452 httpPassword, httpsUser, httpsPassword);
455 String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
460 // LOAD THE AUTHORS FROM THE authors.props file
461 String authorDetails = resolveResourceURLFor("/authors.props");
465 if (authorDetails != null)
467 URL localJarFileURL = new URL(authorDetails);
468 InputStream in = localJarFileURL.openStream();
469 applicationProperties.load(in);
472 } catch (Exception ex)
474 System.out.println("Error reading author details: " + ex);
475 authorDetails = null;
477 if (authorDetails == null)
479 applicationProperties.remove("AUTHORS");
480 applicationProperties.remove("AUTHORFNAMES");
481 applicationProperties.remove("YEAR");
484 loadBuildProperties(false);
487 .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
489 SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
490 .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
492 SiftsSettings.setFailSafePIDThreshold(
493 jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
494 DEFAULT_FAIL_SAFE_PID_THRESHOLD));
496 SiftsSettings.setCacheThresholdInDays(
497 jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
498 DEFAULT_CACHE_THRESHOLD_IN_DAYS));
500 IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
501 "http://www.jalview.org/services/identifiers"));
502 IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
504 StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
505 .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
506 StructureImportSettings
507 .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
508 // StructureImportSettings
509 // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
510 // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
512 String jnlpVersion = System.getProperty("jalview.version");
514 // jnlpVersion will be null if a latest version check for the channel needs
516 // Dont do this check if running in headless mode
518 if (jnlpVersion == null && getDefault("VERSION_CHECK", true)
519 && (System.getProperty("java.awt.headless") == null || System
520 .getProperty("java.awt.headless").equals("false")))
523 class VersionChecker extends Thread
528 String orgtimeout = System
529 .getProperty("sun.net.client.defaultConnectTimeout");
530 if (orgtimeout == null)
533 System.out.println("# INFO: Setting default net timeout to "
534 + orgtimeout + " seconds.");
536 String remoteVersion = null;
539 System.setProperty("sun.net.client.defaultConnectTimeout",
541 java.net.URL url = new java.net.URL(Cache
542 .getDefault("www.jalview.org", "http://www.jalview.org")
543 + "/webstart/jalview.jnlp");
544 BufferedReader in = new BufferedReader(
545 new InputStreamReader(url.openStream()));
547 while ((line = in.readLine()) != null)
549 if (line.indexOf("jalview.version") == -1)
554 line = line.substring(line.indexOf("value=") + 7);
555 line = line.substring(0, line.lastIndexOf("\""));
556 remoteVersion = line;
559 } catch (Exception ex)
562 "Non-fatal exception when checking version at www.jalview.org :");
563 System.out.println(ex);
564 remoteVersion = getProperty("VERSION");
566 System.setProperty("sun.net.client.defaultConnectTimeout",
569 setProperty("LATEST_VERSION", remoteVersion);
573 VersionChecker vc = new VersionChecker();
578 if (jnlpVersion != null)
580 setProperty("LATEST_VERSION", jnlpVersion);
584 applicationProperties.remove("LATEST_VERSION");
588 // LOAD USERDEFINED COLOURS
589 Cache.initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
590 jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
595 * construct a resource URL for the given absolute resource pathname
597 * @param resourcePath
600 private static String resolveResourceURLFor(String resourcePath)
603 if (Platform.isJS() || !Cache.class.getProtectionDomain()
604 .getCodeSource().getLocation().toString().endsWith(".jar"))
608 url = Cache.class.getResource(resourcePath).toString();
609 } catch (Exception ex)
611 System.err.println("Failed to resolve resource " + resourcePath
612 + ": " + ex.getMessage());
617 url = "jar:".concat(Cache.class.getProtectionDomain().getCodeSource()
618 .getLocation().toString().concat("!" + resourcePath));
623 public static void loadBuildProperties(boolean reportVersion)
625 String codeInstallation = getProperty("INSTALLATION");
626 boolean printVersion = codeInstallation == null;
629 * read build properties - from the Jalview jar for a Java distribution,
630 * or from codebase file in test or JalviewJS context
634 String buildDetails = resolveResourceURLFor("/.build_properties");
635 URL localJarFileURL = new URL(buildDetails);
636 InputStream in = localJarFileURL.openStream();
637 applicationProperties.load(in);
639 } catch (Exception ex)
641 System.out.println("Error reading build details: " + ex);
642 applicationProperties.remove("VERSION");
644 String codeVersion = getProperty("VERSION");
645 codeInstallation = getProperty("INSTALLATION");
647 if (codeVersion == null)
649 // THIS SHOULD ONLY BE THE CASE WHEN TESTING!!
650 codeVersion = "Test";
651 codeInstallation = "";
655 codeInstallation = " (" + codeInstallation + ")";
657 setProperty("VERSION", codeVersion);
658 new BuildDetails(codeVersion, null, codeInstallation);
659 if (printVersion && reportVersion)
662 "Jalview Version: " + codeVersion + codeInstallation);
666 private static void deleteBuildProperties()
668 applicationProperties.remove("LATEST_VERSION");
669 applicationProperties.remove("VERSION");
670 applicationProperties.remove("AUTHORS");
671 applicationProperties.remove("AUTHORFNAMES");
672 applicationProperties.remove("YEAR");
673 applicationProperties.remove("BUILD_DATE");
674 applicationProperties.remove("INSTALLATION");
678 * Gets Jalview application property of given key. Returns null if key not
684 * @return Property value
686 public static String getProperty(String key)
688 String prop = applicationProperties.getProperty(key);
689 if (prop == null && Platform.isJS())
691 prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
692 + "_" + JS_PROPERTY_PREFIX + key);
698 * These methods are used when checking if the saved preference is different
699 * to the default setting
702 public static boolean getDefault(String property, boolean def)
704 String string = getProperty(property);
707 def = Boolean.valueOf(string).booleanValue();
713 public static int getDefault(String property, int def)
715 String string = getProperty(property);
720 def = Integer.parseInt(string);
721 } catch (NumberFormatException e)
723 System.out.println("Error parsing int property '" + property
724 + "' with value '" + string + "'");
732 * Answers the value of the given property, or the supplied default value if
733 * the property is not set
735 public static String getDefault(String property, String def)
737 String value = getProperty(property);
738 return value == null ? def : value;
742 * Stores property in the file "HOME_DIR/.jalview_properties"
747 * String value of property
749 * @return previous value of property (or null)
751 public static Object setProperty(String key, String obj)
753 Object oldValue = null;
756 oldValue = applicationProperties.setProperty(key, obj);
757 if (propertiesFile != null && !propsAreReadOnly)
759 FileOutputStream out = new FileOutputStream(propertiesFile);
760 applicationProperties.store(out, "---JalviewX Properties File---");
763 } catch (Exception ex)
766 "Error setting property: " + key + " " + obj + "\n" + ex);
772 * remove the specified property from the jalview properties file
776 public static void removeProperty(String string)
778 applicationProperties.remove(string);
783 * save the properties to the jalview properties path
785 public static void saveProperties()
787 if (!propsAreReadOnly)
791 FileOutputStream out = new FileOutputStream(propertiesFile);
792 applicationProperties.store(out, "---JalviewX Properties File---");
794 } catch (Exception ex)
796 System.out.println("Error saving properties: " + ex);
802 * internal vamsas class discovery state
804 private static int vamsasJarsArePresent = -1;
807 * Searches for vamsas client classes on class path.
809 * @return true if vamsas client is present on classpath
811 public static boolean vamsasJarsPresent()
813 if (vamsasJarsArePresent == -1)
817 if (jalview.jbgui.GDesktop.class.getClassLoader()
818 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
820 jalview.bin.Cache.log.debug(
821 "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
822 vamsasJarsArePresent = 1;
823 Logger lvclient = Logger.getLogger("uk.ac.vamsas");
824 lvclient.setLevel(Level.toLevel(Cache
825 .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
827 lvclient.addAppender(log.getAppender("JalviewLogger"));
828 // Tell the user that debug is enabled
829 lvclient.debug("Jalview Vamsas Client Debugging Output Follows.");
831 } catch (Exception e)
833 vamsasJarsArePresent = 0;
834 jalview.bin.Cache.log.debug("Vamsas Classes are not present");
837 return (vamsasJarsArePresent > 0);
841 * internal vamsas class discovery state
843 private static int groovyJarsArePresent = -1;
846 * Searches for vamsas client classes on class path.
848 * @return true if vamsas client is present on classpath
850 public static boolean groovyJarsPresent()
852 if (groovyJarsArePresent == -1)
856 if (Cache.class.getClassLoader()
857 .loadClass("groovy.lang.GroovyObject") != null)
859 jalview.bin.Cache.log.debug(
860 "Found Groovy (groovy.lang.GroovyObject can be loaded)");
861 groovyJarsArePresent = 1;
862 Logger lgclient = Logger.getLogger("groovy");
863 lgclient.setLevel(Level.toLevel(Cache
864 .getDefault("logs.Groovy.Level", Level.INFO.toString())));
866 lgclient.addAppender(log.getAppender("JalviewLogger"));
867 // Tell the user that debug is enabled
868 lgclient.debug("Jalview Groovy Client Debugging Output Follows.");
872 groovyJarsArePresent = 0;
873 jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
874 } catch (Exception e)
876 groovyJarsArePresent = 0;
877 jalview.bin.Cache.log.debug("Groovy Classes are not present");
880 return (groovyJarsArePresent > 0);
884 * GA tracker object - actually JGoogleAnalyticsTracker null if tracking not
887 protected static Object tracker = null;
889 protected static Class trackerfocus = null;
891 protected static Class jgoogleanalyticstracker = null;
894 * Initialise the google tracker if it is not done already.
896 public static void initGoogleTracker()
900 if (jgoogleanalyticstracker == null)
902 // try to get the tracker class
905 jgoogleanalyticstracker = Cache.class.getClassLoader().loadClass(
906 "com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker");
907 trackerfocus = Cache.class.getClassLoader()
908 .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
909 } catch (Exception e)
912 "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
914 jgoogleanalyticstracker = null;
919 // now initialise tracker
920 Exception re = null, ex = null;
922 String vrs = "No Version Accessible";
925 // Google analytics tracking code for Library Finder
926 tracker = jgoogleanalyticstracker
927 .getConstructor(new Class[]
928 { String.class, String.class, String.class })
929 .newInstance(new Object[]
931 (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
932 + jalview.bin.Cache.getDefault("BUILD_DATE",
935 jgoogleanalyticstracker
936 .getMethod("trackAsynchronously", new Class[]
938 .invoke(tracker, new Object[]
939 { trackerfocus.getConstructor(new Class[] { String.class })
940 .newInstance(new Object[]
941 { "Application Started." }) });
942 } catch (RuntimeException e)
945 } catch (Exception e)
952 if (re != null || ex != null || err != null)
958 log.debug("Caught runtime exception in googletracker init:",
964 "Failed to initialise GoogleTracker for Jalview Desktop with version "
971 "Whilst initing GoogleTracker for Jalview Desktop version "
981 "Debug: Caught runtime exception in googletracker init:"
983 re.printStackTrace();
988 "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version "
990 ex.printStackTrace();
996 "ERROR: Whilst initing GoogleTracker for Jalview Desktop version "
998 err.printStackTrace();
1004 log.debug("Successfully initialised tracker.");
1010 * get the user's default colour if available
1016 public static Color getDefaultColour(String property, Color defcolour)
1018 String colprop = getProperty(property);
1019 if (colprop == null)
1023 Color col = ColorUtils.parseColourString(colprop);
1026 log.warn("Couldn't parse '" + colprop + "' as a colour for "
1029 return (col == null) ? defcolour : col;
1033 * store a colour as a Jalview user default property
1038 public static void setColourProperty(String property, Color colour)
1040 setProperty(property, jalview.util.Format.getHexString(colour));
1044 * Stores a formatted date in a jalview property, using a fixed locale.
1046 * @param propertyName
1048 * @return the formatted date string
1050 public static String setDateProperty(String propertyName, Date date)
1052 String formatted = date_format.format(date);
1053 setProperty(propertyName, formatted);
1058 * Reads a date stored in a Jalview property, parses it (using a fixed locale
1059 * format) and returns as a Date, or null if parsing fails
1061 * @param propertyName
1065 public static Date getDateProperty(String propertyName)
1067 String val = getProperty(propertyName);
1072 return date_format.parse(val);
1073 } catch (Exception ex)
1075 System.err.println("Invalid or corrupt date in property '"
1076 + propertyName + "' : value was '" + val + "'");
1083 * get and parse a property as an integer. send any parsing problems to
1087 * @return null or Integer
1089 public static Integer getIntegerProperty(String property)
1091 String val = getProperty(property);
1092 if (val != null && (val = val.trim()).length() > 0)
1096 return Integer.valueOf(val);
1097 } catch (NumberFormatException x)
1099 System.err.println("Invalid integer in property '" + property
1100 + "' (value was '" + val + "')");
1107 * Set the specified value, or remove it if null or empty. Does not save the
1113 public static void setOrRemove(String propName, String value)
1115 if (propName == null)
1119 if (value == null || value.trim().length() < 1)
1121 Cache.applicationProperties.remove(propName);
1125 Cache.applicationProperties.setProperty(propName, value);
1130 * Loads in user colour schemes from files.
1133 * a '|'-delimited list of file paths
1135 public static void initUserColourSchemes(String files)
1137 if (files == null || files.length() == 0)
1142 // In case colours can't be loaded, we'll remove them
1143 // from the default list here.
1144 StringBuffer coloursFound = new StringBuffer();
1145 StringTokenizer st = new StringTokenizer(files, "|");
1146 while (st.hasMoreElements())
1148 String file = st.nextToken();
1151 UserColourScheme ucs = ColourSchemeLoader.loadColourScheme(file);
1154 if (coloursFound.length() > 0)
1156 coloursFound.append("|");
1158 coloursFound.append(file);
1159 ColourSchemes.getInstance().registerColourScheme(ucs);
1161 } catch (Exception ex)
1163 System.out.println("Error loading User ColourFile\n" + ex);
1166 if (!files.equals(coloursFound.toString()))
1168 if (coloursFound.toString().length() > 1)
1170 setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
1171 coloursFound.toString());
1175 applicationProperties
1176 .remove(UserDefinedColours.USER_DEFINED_COLOURS);
1182 * Initial logging information helper for various versions output
1186 * @param defaultValue
1188 private static void appendIfNotNull(StringBuilder sb, String prefix,
1189 String value, String suffix, String defaultValue)
1191 if (value == null && defaultValue == null)
1195 String line = prefix + (value != null ? value : defaultValue) + suffix;
1201 * @return Jalview version, build details and JVM platform version for console
1203 public static String getVersionDetailsForConsole()
1205 StringBuilder sb = new StringBuilder();
1206 sb.append("Jalview Version: ");
1207 sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST"));
1209 sb.append("Jalview Installation: ");
1210 sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown"));
1212 sb.append("Build Date: ");
1213 sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1215 sb.append("Java version: ");
1216 sb.append(System.getProperty("java.version"));
1218 sb.append(System.getProperty("os.arch"));
1220 sb.append(System.getProperty("os.name"));
1222 sb.append(System.getProperty("os.version"));
1224 appendIfNotNull(sb, "Install4j version: ",
1225 System.getProperty("sys.install4jVersion"), "\n", null);
1226 appendIfNotNull(sb, "Install4j template version: ",
1227 System.getProperty("installer_template_version"), "\n", null);
1228 appendIfNotNull(sb, "Launcher version: ",
1229 System.getProperty("launcher_version"), "\n", null);
1230 LookAndFeel laf = UIManager.getLookAndFeel();
1231 String lafName = laf == null ? "Not obtained" : laf.getName();
1232 String lafClass = laf == null ? "unknown" : laf.getClass().getName();
1233 sb.append("LookAndFeel: ");
1236 sb.append(lafClass);
1238 // Not displayed in release version ( determined by possible version number
1239 // regex 9[9.]*9[.-_a9]* )
1240 if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$",
1241 jalview.bin.Cache.getDefault("VERSION", "TEST")))
1243 appendIfNotNull(sb, "Getdown appdir: ",
1244 System.getProperty("getdownappdir"), "\n", null);
1245 appendIfNotNull(sb, "Java home: ", System.getProperty("java.home"),
1248 return sb.toString();
1253 * @return build details as reported in splashscreen
1255 public static String getBuildDetailsForSplash()
1257 // consider returning more human friendly info
1258 // eg 'built from Source' or update channel
1259 return jalview.bin.Cache.getDefault("INSTALLATION", "unknown");
1262 public static String getStackTraceString(Throwable t)
1264 StringWriter sw = new StringWriter();
1265 PrintWriter pw = new PrintWriter(sw);
1266 t.printStackTrace(pw);
1267 return sw.toString();
1270 // proxy properties methods
1271 public static void resetProxyProperties()
1273 setProxyProperties(startupProxyProperties[0], startupProxyProperties[1],
1274 startupProxyProperties[2], startupProxyProperties[3],
1275 startupProxyProperties[4], startupProxyProperties[5],
1276 startupProxyProperties[6], startupProxyProperties[7]);
1277 StringBuilder sb = new StringBuilder();
1278 sb.append("Setting proxy properties to: http.proxyHost=")
1279 .append(startupProxyProperties[0]).append(", http.proxyPort=")
1280 .append(startupProxyProperties[1])
1281 .append(startupProxyProperties[4] != null
1282 && !startupProxyProperties[4].isEmpty()
1283 ? " [" + startupProxyProperties[4] + "]"
1285 .append(", https.proxyHost=").append(startupProxyProperties[2])
1286 .append(", https.proxyPort=").append(startupProxyProperties[3])
1287 .append(startupProxyProperties[6] != null
1288 && !startupProxyProperties[6].isEmpty()
1289 ? " [" + startupProxyProperties[6] + "]"
1292 Cache.debug(sb.toString());
1295 public static void setProxyProperties(String httpHost, String httpPort,
1296 String httpsHost, String httpsPort, String httpUser,
1297 String httpPassword)
1299 setProxyProperties(httpHost, httpPort, httpsHost, httpsPort, httpUser,
1300 httpPassword, httpUser, httpPassword);
1303 public static void setProxyProperties(String httpHost, String httpPort,
1304 String httpsHost, String httpsPort, String httpUser,
1305 String httpPassword, String httpsUser, String httpsPassword)
1307 setOrClearSystemProperty("http.proxyHost", httpHost);
1308 setOrClearSystemProperty("http.proxyPort", httpPort);
1309 setOrClearSystemProperty("https.proxyHost", httpsHost);
1310 setOrClearSystemProperty("https.proxyPort", httpsPort);
1311 setOrClearSystemProperty("http.proxyUser", httpUser);
1312 setOrClearSystemProperty("http.proxyPassword", httpPassword);
1313 setOrClearSystemProperty("https.proxyUser", httpsUser);
1314 setOrClearSystemProperty("https.proxyPassword", httpsPassword);
1315 if (httpUser != null || httpsUser != null)
1319 Authenticator.setDefault(new Authenticator()
1322 protected PasswordAuthentication getPasswordAuthentication()
1324 if (getRequestorType() == RequestorType.PROXY)
1328 if (getRequestingScheme().equalsIgnoreCase("http")
1329 && getRequestingHost().equalsIgnoreCase(httpHost)
1330 && getRequestingPort() == Integer.valueOf(httpPort))
1332 return new PasswordAuthentication(httpUser,
1333 httpPassword == null ? new char[] {}
1334 : httpPassword.toCharArray());
1336 if (getRequestingScheme().equalsIgnoreCase("https")
1337 && getRequestingHost().equalsIgnoreCase(httpsHost)
1338 && getRequestingPort() == Integer
1339 .valueOf(httpsPort))
1341 return new PasswordAuthentication(httpsUser,
1342 httpsPassword == null ? new char[] {}
1343 : httpsPassword.toCharArray());
1345 } catch (NumberFormatException e)
1347 Cache.error("Problem with proxy port values [http:"
1348 + httpPort + ", https:" + httpsPort + "]");
1351 // non proxy request
1355 // required to re-enable basic authentication (should be okay for a
1357 System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
1358 } catch (SecurityException e)
1360 Cache.error("Could not set default Authenticator");
1361 Cache.debug(getStackTraceString(e));
1366 // reset the Authenticator to protect http.proxyUser and
1367 // http.proxyPassword Just In Case
1368 Authenticator.setDefault(new Authenticator()
1371 protected PasswordAuthentication getPasswordAuthentication()
1378 // clear localhost from proxying unless nonProxyHosts already set (not
1379 // currently configurable in Preferences)
1380 String nonProxyHosts = startupProxyProperties[8];
1381 System.setProperty("http.nonProxyHosts",
1382 nonProxyHosts == null ? "localhost" : nonProxyHosts);
1385 public static void setOrClearSystemProperty(String key, String value)
1393 System.clearProperty(key);
1397 System.setProperty(key, value);
1401 public final static int DEBUG = 10;
1403 public final static int INFO = 20;
1405 public final static int WARN = 30;
1407 public final static int ERROR = 40;
1409 public static boolean println(int level, String message)
1411 if (Cache.log == null)
1414 System.err.println(message);
1416 System.out.println(message);
1421 Cache.log.warn(message);
1423 else if (level >= INFO)
1425 Cache.log.info(message);
1429 Cache.log.debug(message);
1434 public static void debug(String message)
1436 println(DEBUG, message);
1439 public static void info(String message)
1441 println(INFO, message);
1444 public static void warn(String message)
1446 println(WARN, message);
1449 public static void error(String message)
1451 println(ERROR, message);