From a1984b1c8c273ed33c7ce9283039f4027dcae2de Mon Sep 17 00:00:00 2001 From: Ben Soares Date: Fri, 11 Feb 2022 03:34:22 +0000 Subject: [PATCH] JAL-3949 Complete new abstracted logging framework in jalview.log. Updated log calls for this. Removal of jalview.javascript.log4j. Improvements to the Java Console (controllable autoscrolling). --- gradle.properties | 2 +- src/jalview/analysis/AlignmentUtils.java | 2 +- src/jalview/analysis/GeneticCodes.java | 6 +- src/jalview/analysis/PCA.java | 2 +- src/jalview/analysis/TreeModel.java | 9 +- src/jalview/bin/Cache.java | 376 ++++++++++++-------- src/jalview/bin/Jalview.java | 91 +++-- src/jalview/ext/ensembl/EnsemblLookup.java | 2 +- src/jalview/ext/ensembl/EnsemblSeqProxy.java | 2 +- src/jalview/ext/htsjdk/VCFReader.java | 2 +- src/jalview/ext/jmol/JalviewJmolBinding.java | 4 +- src/jalview/ext/pymol/PymolManager.java | 20 +- .../ext/rbvi/chimera/JalviewChimeraBinding.java | 12 +- src/jalview/ext/so/SequenceOntology.java | 10 +- src/jalview/fts/core/GFTSPanel.java | 2 +- .../fts/service/alphafold/AlphafoldRestClient.java | 3 +- .../service/threedbeacons/TDBeaconsFTSPanel.java | 2 +- src/jalview/gui/APQHandlers.java | 3 +- src/jalview/gui/AlignFrame.java | 54 +-- src/jalview/gui/AlignViewport.java | 20 +- src/jalview/gui/AlignmentPanel.java | 6 +- src/jalview/gui/AppJmol.java | 10 +- src/jalview/gui/AppJmolBinding.java | 2 +- src/jalview/gui/BlogReader.java | 32 +- src/jalview/gui/ChimeraViewFrame.java | 6 +- src/jalview/gui/Console.java | 95 +++-- src/jalview/gui/CrossRefAction.java | 2 +- src/jalview/gui/CutAndPasteHtmlTransfer.java | 3 +- src/jalview/gui/CutAndPasteTransfer.java | 5 +- src/jalview/gui/Desktop.java | 86 +++-- src/jalview/gui/FeatureTypeSettings.java | 2 +- src/jalview/gui/OOMWarning.java | 11 +- src/jalview/gui/PCAPanel.java | 2 +- src/jalview/gui/PopupMenu.java | 8 +- src/jalview/gui/Preferences.java | 10 +- src/jalview/gui/PromptUserConfig.java | 32 +- src/jalview/gui/PymolBindingModel.java | 4 +- src/jalview/gui/PymolViewer.java | 8 +- src/jalview/gui/RotatableCanvas.java | 2 +- src/jalview/gui/SeqPanel.java | 2 +- src/jalview/gui/SequenceFetcher.java | 2 +- src/jalview/gui/StructureChooser.java | 4 +- src/jalview/gui/StructureViewer.java | 6 +- src/jalview/gui/StructureViewerBase.java | 2 +- src/jalview/gui/TreePanel.java | 7 +- src/jalview/gui/UserQuestionnaireCheck.java | 17 +- src/jalview/gui/VamsasApplication.java | 99 +++--- src/jalview/gui/WsJobParameters.java | 4 +- src/jalview/gui/WsParamSetManager.java | 20 +- .../ThreeDBStructureChooserQuerySource.java | 2 +- src/jalview/io/BackupFilesPresetEntry.java | 2 +- src/jalview/io/BioJsHTMLOutput.java | 5 +- src/jalview/io/EMBLLikeFlatFile.java | 18 +- src/jalview/io/EmblFlatFile.java | 2 +- src/jalview/io/FileLoader.java | 2 +- src/jalview/io/FileParse.java | 2 +- src/jalview/io/FormatAdapter.java | 8 +- src/jalview/io/HtmlSvgOutput.java | 2 +- src/jalview/io/ModellerDescription.java | 5 +- src/jalview/io/StockholmFile.java | 31 +- src/jalview/io/VamsasAppDatastore.java | 103 +++--- src/jalview/io/vamsas/DatastoreItem.java | 27 +- src/jalview/io/vamsas/DatastoreRegistry.java | 7 +- src/jalview/io/vamsas/Dbref.java | 14 +- src/jalview/io/vamsas/Rangetype.java | 4 +- src/jalview/io/vamsas/Sequencefeature.java | 11 +- src/jalview/io/vamsas/Sequencemapping.java | 33 +- src/jalview/io/vamsas/Tree.java | 22 +- src/jalview/io/vcf/VCFLoader.java | 18 +- src/jalview/javascript/MouseOverListener.java | 2 +- src/jalview/javascript/log4j/Appender.java | 9 - src/jalview/javascript/log4j/ConsoleAppender.java | 41 --- src/jalview/javascript/log4j/Layout.java | 86 ----- src/jalview/javascript/log4j/Level.java | 273 -------------- src/jalview/javascript/log4j/Logger.java | 194 ---------- src/jalview/javascript/log4j/Priority.java | 204 ----------- src/jalview/javascript/log4j/SimpleLayout.java | 55 --- src/jalview/javascript/log4j/WriterAppender.java | 23 -- src/jalview/javascript/log4j/spi/LoggingEvent.java | 51 --- .../javascript/log4j/spi/OptionHandler.java | 8 - src/jalview/jbgui/GAlignFrame.java | 8 +- src/jalview/jbgui/GPreferences.java | 10 +- src/jalview/jbgui/GWsPreferences.java | 3 +- src/jalview/log/JLogger.java | 181 ++++++++++ src/jalview/log/JLoggerI.java | 41 +++ src/jalview/log/JLoggerLog4j.java | 137 +++++++ src/jalview/{gui => log}/JalviewAppender.java | 34 +- src/jalview/project/Jalview2XML.java | 119 ++----- .../structure/StructureSelectionManager.java | 6 +- .../structures/models/AAStructureBindingModel.java | 2 +- src/jalview/urls/UrlLinkTableModel.java | 2 +- src/jalview/util/BrowserLauncher.java | 4 +- src/jalview/util/Log4j.java | 160 ++++++++- src/jalview/util/MapList.java | 4 +- src/jalview/util/MappingUtils.java | 8 +- src/jalview/util/MessageManager.java | 6 +- src/jalview/ws/AWSThread.java | 14 +- src/jalview/ws/DBRefFetcher.java | 4 +- src/jalview/ws/dbsources/EmblFlatfileSource.java | 2 +- src/jalview/ws/dbsources/EmblXmlSource.java | 2 +- src/jalview/ws/dbsources/Xfam.java | 5 +- src/jalview/ws/jws1/Discoverer.java | 46 ++- src/jalview/ws/jws1/JPredClient.java | 2 +- src/jalview/ws/jws1/JPredThread.java | 24 +- src/jalview/ws/jws1/MsaWSThread.java | 10 +- src/jalview/ws/jws1/SeqSearchWSClient.java | 3 +- src/jalview/ws/jws1/SeqSearchWSThread.java | 8 +- src/jalview/ws/jws2/AADisorderClient.java | 3 +- src/jalview/ws/jws2/AbstractJabaCalcWorker.java | 3 +- src/jalview/ws/jws2/JabaWsServerQuery.java | 6 +- src/jalview/ws/jws2/Jws2Client.java | 4 +- src/jalview/ws/jws2/Jws2Discoverer.java | 16 +- src/jalview/ws/jws2/MsaWSThread.java | 16 +- src/jalview/ws/rest/HttpResultSet.java | 12 +- src/jalview/ws/rest/RestClient.java | 2 +- src/jalview/ws/rest/RestJobThread.java | 32 +- src/jalview/ws/seqfetcher/ASequenceFetcher.java | 2 +- test/jalview/util/Log4jTest.java | 199 +++++++++++ test/jalview/util/log4jTestProps.jvprops | 15 + 119 files changed, 1675 insertions(+), 1857 deletions(-) delete mode 100644 src/jalview/javascript/log4j/Appender.java delete mode 100644 src/jalview/javascript/log4j/ConsoleAppender.java delete mode 100644 src/jalview/javascript/log4j/Layout.java delete mode 100644 src/jalview/javascript/log4j/Level.java delete mode 100644 src/jalview/javascript/log4j/Logger.java delete mode 100644 src/jalview/javascript/log4j/Priority.java delete mode 100644 src/jalview/javascript/log4j/SimpleLayout.java delete mode 100644 src/jalview/javascript/log4j/WriterAppender.java delete mode 100644 src/jalview/javascript/log4j/spi/LoggingEvent.java delete mode 100644 src/jalview/javascript/log4j/spi/OptionHandler.java create mode 100644 src/jalview/log/JLogger.java create mode 100644 src/jalview/log/JLoggerI.java create mode 100644 src/jalview/log/JLoggerLog4j.java rename src/jalview/{gui => log}/JalviewAppender.java (72%) create mode 100644 test/jalview/util/Log4jTest.java create mode 100644 test/jalview/util/log4jTestProps.jvprops diff --git a/gradle.properties b/gradle.properties index 21360df..8eec281 100644 --- a/gradle.properties +++ b/gradle.properties @@ -223,7 +223,7 @@ j2s.excluded.paths = test;testng;util #j2s.compiler.nonqualified.classes = null #j2s.compiler.mode = debug #a semicolon-separated list of package (foo.) or class (foo.bar) replacements to be made -j2s.class.replacements = org.apache.log4j.->jalview.javascript.log4j. +#j2s.class.replacements = org.apache.logging.log4j.->jalview.javascript.log4j. j2s.template.html = utils/jalviewjs/template.html j2s_coretemplate_html = utils/jalviewjs/coretemplate.html #output file name for logging methods declared - delete the file to regenerate a listing diff --git a/src/jalview/analysis/AlignmentUtils.java b/src/jalview/analysis/AlignmentUtils.java index f95ff73..fd540da 100644 --- a/src/jalview/analysis/AlignmentUtils.java +++ b/src/jalview/analysis/AlignmentUtils.java @@ -2056,7 +2056,7 @@ public class AlignmentUtils } else { - Cache.log.error( + Cache.error( "JAL-2154 regression: warning - found (and ignored) a duplicate CDS sequence:" + mtch.toString()); } } diff --git a/src/jalview/analysis/GeneticCodes.java b/src/jalview/analysis/GeneticCodes.java index 8d69b0b..59b698d 100644 --- a/src/jalview/analysis/GeneticCodes.java +++ b/src/jalview/analysis/GeneticCodes.java @@ -162,7 +162,7 @@ public final class GeneticCodes } } catch (IOException | NullPointerException e) { - Cache.log.error( + Cache.error( "Error reading genetic codes data file " + fileName + ": " + e.getMessage()); } @@ -217,7 +217,7 @@ public final class GeneticCodes } } catch (IOException e) { - Cache.log.error( + Cache.error( "Error reading nucleotide ambiguity codes data file: " + e.getMessage()); } @@ -294,7 +294,7 @@ public final class GeneticCodes line.lastIndexOf(QUOTE)); if (aminos.length() != NUCS_COUNT_CUBED) // 4 * 4 * 4 combinations { - Cache.log.error("wrong data length in code table: " + line); + Cache.error("wrong data length in code table: " + line); } else { diff --git a/src/jalview/analysis/PCA.java b/src/jalview/analysis/PCA.java index d51f00e..60dd901 100755 --- a/src/jalview/analysis/PCA.java +++ b/src/jalview/analysis/PCA.java @@ -220,7 +220,7 @@ public class PCA implements Runnable eigenMatrix.tqli(); } catch (Exception q) { - Cache.log.error("Error computing PCA: " + q.getMessage()); + Cache.error("Error computing PCA: " + q.getMessage()); q.printStackTrace(); } } diff --git a/src/jalview/analysis/TreeModel.java b/src/jalview/analysis/TreeModel.java index a50634e..4d5e4b2 100644 --- a/src/jalview/analysis/TreeModel.java +++ b/src/jalview/analysis/TreeModel.java @@ -20,6 +20,7 @@ */ package jalview.analysis; +import jalview.bin.Cache; import jalview.datamodel.AlignmentView; import jalview.datamodel.BinaryNode; import jalview.datamodel.NodeTransformI; @@ -155,8 +156,8 @@ public class TreeModel if (one2many.contains(nam)) { // countOne2Many++; - // if (jalview.bin.Cache.log.isDebugEnabled()) - // jalview.bin.Cache.log.debug("One 2 many relationship for + // if (Cache.isDebugEnabled()) + // Cache.debug("One 2 many relationship for // "+nam.getName()); } else @@ -171,8 +172,8 @@ public class TreeModel j.setPlaceholder(true); } } - // if (jalview.bin.Cache.log.isDebugEnabled() && countOne2Many>0) { - // jalview.bin.Cache.log.debug("There were "+countOne2Many+" alignment + // if (Cache.isDebugEnabled() && countOne2Many>0) { + // Cache.debug("There were "+countOne2Many+" alignment // sequence ids (out of "+one2many.size()+" unique ids) linked to two or // more leaves."); // } diff --git a/src/jalview/bin/Cache.java b/src/jalview/bin/Cache.java index 250f378..1a4f341 100755 --- a/src/jalview/bin/Cache.java +++ b/src/jalview/bin/Cache.java @@ -47,18 +47,11 @@ import java.util.regex.Pattern; import javax.swing.LookAndFeel; import javax.swing.UIManager; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.config.Configurator; -import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; -import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; -import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory; -import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; - import jalview.datamodel.PDBEntry; import jalview.gui.Preferences; import jalview.gui.UserDefinedColours; +import jalview.log.JLogger; +import jalview.log.JLoggerLog4j; import jalview.schemes.ColourSchemeLoader; import jalview.schemes.ColourSchemes; import jalview.schemes.UserColourScheme; @@ -280,7 +273,10 @@ public class Cache /** * Initialises the Jalview Application Log */ - public static Logger log; + + public final static String JALVIEW_LOGGER_NAME = "JalviewLogger"; + + public static JLoggerLog4j log; // save the proxy properties set at startup public final static String[] startupProxyProperties = { @@ -325,45 +321,58 @@ public class Cache private final static String JS_PROPERTY_PREFIX = "jalview_"; - public static void initLogger() + public final static String LOGGING_TEST_MESSAGE = "Logging to STDERR"; + + public static JLogger.LogLevel getCachedLogLevel() + { + return getCachedLogLevel(JALVIEWLOGLEVEL); + } + + public static JLogger.LogLevel getCachedLogLevel(String key) + { + return JLogger.toLevel(Cache.getDefault(key, "INFO")); + } + + public static boolean initLogger() { if (log != null) { - return; + return true; } try { - // configure the root logger to stderr - ConfigurationBuilder builder = ConfigurationBuilderFactory - .newConfigurationBuilder(); - AppenderComponentBuilder consoleApp = builder.newAppender("stderr", - "Console"); - builder.add(consoleApp); - Configurator.initialize(builder.build()); + JLogger.LogLevel cachedLevel = getCachedLogLevel(); + if (!Platform.isJS()) + { + Log4j.init(cachedLevel); + } // log output - Logger laxis = LogManager.getLogger("org.apache.axis"); - log = LogManager.getLogger("jalview.bin.Jalview"); - - Log4j.setLevel(laxis, Level.toLevel( - Cache.getDefault("logs.Axis.Level", Level.INFO.toString()))); - // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller"); - // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level", - // Level.INFO.toString()))); - // we shouldn't need to do this - Log4j.setRootLevel(Level.INFO); - - Log4j.setLevel(log, Level.toLevel(Cache - .getDefault("logs.Jalview.level", Level.INFO.toString()))); - // laxis.addAppender(ap); - // lcastor.addAppender(ap); - // jalview.bin.Cache.log.addAppender(ap); + // is laxis used? Does getLogger do anything without a Logger object? + // Logger laxis = Log4j.getLogger("org.apache.axis", myLevel); + JLoggerLog4j.getLogger("org.apache.axis", cachedLevel); + + // The main application logger + log = JLoggerLog4j.getLogger(JALVIEW_LOGGER_NAME, cachedLevel); + } catch (NoClassDefFoundError e) + { + System.err.println("Could not initialise the logger framework"); + e.printStackTrace(); + } + + // Test message + if (log != null) + { + // Logging test message should got through the logger object + if (log.loggerExists()) + log.debug(LOGGING_TEST_MESSAGE); // Tell the user that debug is enabled - log.debug(ChannelProperties.getProperty("app_name") + Cache.debug(ChannelProperties.getProperty("app_name") + " Debugging Output Follows."); - } catch (Exception ex) + return true; + } + else { - System.err.println("Problems initializing the log4j system\n"); - ex.printStackTrace(System.err); + return false; } } @@ -509,27 +518,27 @@ public class Cache SiftsSettings .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false)); - SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache + SiftsSettings.setSiftDownloadDirectory(Cache .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR)); SiftsSettings.setFailSafePIDThreshold( - jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold", + Cache.getDefault("sifts_fail_safe_pid_threshold", DEFAULT_FAIL_SAFE_PID_THRESHOLD)); SiftsSettings.setCacheThresholdInDays( - jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days", + Cache.getDefault("sifts_cache_threshold_in_days", DEFAULT_CACHE_THRESHOLD_IN_DAYS)); IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL", "https://www.jalview.org/services/identifiers")); IdOrgSettings.setDownloadLocation(ID_ORG_FILE); - StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache - .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT)); + StructureImportSettings.setDefaultStructureFileFormat( + Cache.getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT)); StructureImportSettings .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER); // StructureImportSettings - // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault( + // .setDefaultPDBFileParser(Cache.getDefault( // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER)); String jnlpVersion = System.getProperty("jalview.version"); @@ -850,14 +859,11 @@ public class Cache if (jalview.jbgui.GDesktop.class.getClassLoader() .loadClass("uk.ac.vamsas.client.VorbaId") != null) { - log.debug( - "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)"); + debug("Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)"); vamsasJarsArePresent = 1; - Logger lvclient = LogManager.getLogger("uk.ac.vamsas"); - Log4j.setLevel(lvclient, Level.toLevel(Cache - .getDefault("logs.Vamsas.Level", Level.INFO.toString()))); - - Log4j.addAppender(lvclient, log, "JalviewLogger"); + JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas", + getCachedLogLevel("logs.Vamsas.Level")); + JLoggerLog4j.addAppender(lvclient, log, JALVIEW_LOGGER_NAME); // Tell the user that debug is enabled lvclient.debug(ChannelProperties.getProperty("app_name") + " Vamsas Client Debugging Output Follows."); @@ -865,7 +871,7 @@ public class Cache } catch (Exception e) { vamsasJarsArePresent = 0; - log.debug("Vamsas Classes are not present"); + debug("Vamsas Classes are not present"); } } return (vamsasJarsArePresent > 0); @@ -890,14 +896,11 @@ public class Cache if (Cache.class.getClassLoader() .loadClass("groovy.lang.GroovyObject") != null) { - log.debug( - "Found Groovy (groovy.lang.GroovyObject can be loaded)"); + debug("Found Groovy (groovy.lang.GroovyObject can be loaded)"); groovyJarsArePresent = 1; - Logger lgclient = LogManager.getLogger("groovy"); - Log4j.setLevel(lgclient, Level.toLevel(Cache - .getDefault("logs.Groovy.Level", Level.INFO.toString()))); - - Log4j.addAppender(lgclient, log, "JalviewLogger"); + JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy", + getCachedLogLevel("logs.Groovy.Level")); + JLoggerLog4j.addAppender(lgclient, log, JALVIEW_LOGGER_NAME); // Tell the user that debug is enabled lgclient.debug(ChannelProperties.getProperty("app_name") + " Groovy Client Debugging Output Follows."); @@ -905,11 +908,11 @@ public class Cache } catch (Error e) { groovyJarsArePresent = 0; - log.debug("Groovy Classes are not present", e); + debug("Groovy Classes are not present", e); } catch (Exception e) { groovyJarsArePresent = 0; - log.debug("Groovy Classes are not present"); + debug("Groovy Classes are not present"); } } return (groovyJarsArePresent > 0); @@ -943,8 +946,7 @@ public class Cache .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint"); } catch (Exception e) { - log.debug( - "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled."); + debug("com.boxysystems.jgoogleanalytics package is not present - tracking not enabled."); tracker = null; jgoogleanalyticstracker = null; trackerfocus = null; @@ -963,9 +965,8 @@ public class Cache { String.class, String.class, String.class }) .newInstance(new Object[] { ChannelProperties.getProperty("app_name") + " Desktop", - (vrs = jalview.bin.Cache.getProperty("VERSION") + "_" - + jalview.bin.Cache.getDefault("BUILD_DATE", - "unknown")), + (vrs = Cache.getProperty("VERSION") + "_" + + Cache.getDefault("BUILD_DATE", "unknown")), "UA-9060947-1" }); jgoogleanalyticstracker .getMethod("trackAsynchronously", new Class[] @@ -986,57 +987,24 @@ public class Cache } if (re != null || ex != null || err != null) { - if (log != null) + if (re != null) { - if (re != null) - { - log.debug("Caught runtime exception in googletracker init:", - re); - } - if (ex != null) - { - log.warn( - "Failed to initialise GoogleTracker for Jalview Desktop with version " - + vrs, - ex); - } - if (err != null) - { - log.error( - "Whilst initing GoogleTracker for Jalview Desktop version " - + vrs, - err); - } + debug("Caught runtime exception in googletracker init:", re); } - else + if (ex != null) { - if (re != null) - { - System.err.println( - "Debug: Caught runtime exception in googletracker init:" - + vrs); - re.printStackTrace(); - } - if (ex != null) - { - System.err.println( - "Warning: Failed to initialise GoogleTracker for Jalview Desktop with version " - + vrs); - ex.printStackTrace(); - } - - if (err != null) - { - System.err.println( - "ERROR: Whilst initing GoogleTracker for Jalview Desktop version " - + vrs); - err.printStackTrace(); - } + warn("Failed to initialise GoogleTracker for Jalview Desktop with version " + + vrs, ex); + } + if (err != null) + { + error("Whilst initing GoogleTracker for Jalview Desktop version " + + vrs, err); } } else { - log.debug("Successfully initialised tracker."); + debug("Successfully initialised tracker."); } } } @@ -1058,8 +1026,7 @@ public class Cache Color col = ColorUtils.parseColourString(colprop); if (col == null) { - log.warn("Couldn't parse '" + colprop + "' as a colour for " - + property); + warn("Couldn't parse '" + colprop + "' as a colour for " + property); } return (col == null) ? defcolour : col; } @@ -1240,14 +1207,14 @@ public class Cache StringBuilder sb = new StringBuilder(); sb.append(ChannelProperties.getProperty("app_name")) .append(" Version: "); - sb.append(jalview.bin.Cache.getDefault("VERSION", "TEST")); + sb.append(Cache.getDefault("VERSION", "TEST")); sb.append("\n"); sb.append(ChannelProperties.getProperty("app_name")) .append(" Installation: "); - sb.append(jalview.bin.Cache.getDefault("INSTALLATION", "unknown")); + sb.append(Cache.getDefault("INSTALLATION", "unknown")); sb.append("\n"); sb.append("Build Date: "); - sb.append(jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")); + sb.append(Cache.getDefault("BUILD_DATE", "unknown")); sb.append("\n"); sb.append("Java version: "); sb.append(System.getProperty("java.version")); @@ -1275,7 +1242,7 @@ public class Cache // Not displayed in release version ( determined by possible version number // regex 9[9.]*9[.-_a9]* ) if (Pattern.matches("^\\d[\\d\\.]*\\d[\\.\\-\\w]*$", - jalview.bin.Cache.getDefault("VERSION", "TEST"))) + Cache.getDefault("VERSION", "TEST"))) { appendIfNotNull(sb, "Getdown appdir: ", System.getProperty("getdownappdir"), "\n", null); @@ -1295,7 +1262,7 @@ public class Cache { // consider returning more human friendly info // eg 'built from Source' or update channel - return jalview.bin.Cache.getDefault("INSTALLATION", "unknown"); + return Cache.getDefault("INSTALLATION", "unknown"); } public static String getStackTraceString(Throwable t) @@ -1365,7 +1332,7 @@ public class Cache case Cache.PROXYTYPE_NONE: if (!previousProxyType.equals(proxyType)) { - Cache.log.info("Setting no proxy settings"); + Cache.info("Setting no proxy settings"); Cache.setProxyProperties(null, null, null, null, null, null, null, null, null); } @@ -1373,7 +1340,7 @@ public class Cache case Cache.PROXYTYPE_CUSTOM: // always re-set a custom proxy -- it might have changed, particularly // password - Cache.log.info("Setting custom proxy settings"); + Cache.info("Setting custom proxy settings"); boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false); Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null), Cache.getDefault("PROXY_PORT", null), @@ -1387,7 +1354,7 @@ public class Cache proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost"); break; default: // system proxy settings by default - Cache.log.info("Setting system proxy settings"); + Cache.info("Setting system proxy settings"); Cache.resetProxyProperties(); } } @@ -1586,73 +1553,174 @@ public class Cache } } - public final static int TRACE = 10; + public static void trace(String message) + { + if (initLogger()) + { + log.trace(message, null); + } + else + { + System.out.println(message); + } + } + + public static void trace(String message, Throwable t) + { + if (initLogger()) + { + log.trace(message, t); + } + else + { + System.out.println(message); + t.printStackTrace(); + } + } + + public static void debug(String message) + { + if (initLogger()) + { + log.debug(message, null); + } + else + { + System.out.println(message); + } + + } + + public static void debug(String message, Throwable t) + { + if (initLogger()) + { + log.debug(message, t); + } + else + { + System.out.println(message); + t.printStackTrace(); + } + + } - public final static int DEBUG = 20; + public static void info(String message) + { + if (initLogger()) + { + log.info(message, null); + } + else + { + System.out.println(message); + } - public final static int INFO = 30; + } - public final static int WARN = 40; + public static void info(String message, Throwable t) + { + if (initLogger()) + { + log.info(message, t); + } + else + { + System.out.println(message); + t.printStackTrace(); + } - public final static int ERROR = 50; + } - public static boolean println(int level, String message) + public static void warn(String message) { - if (Cache.log == null) + if (initLogger()) { - if (level >= WARN) - System.err.println(message); - else if (level >= INFO) - System.out.println(message); - // not printing debug or trace messages - return false; + log.warn(message, null); } - if (level >= ERROR) + else { - Cache.log.error(message); + System.out.println(message); } - else if (level >= WARN) + + } + + public static void warn(String message, Throwable t) + { + if (initLogger()) { - Cache.log.warn(message); + log.warn(message, t); } - else if (level >= INFO) + else { - Cache.log.info(message); + System.out.println(message); + t.printStackTrace(); } - else if (level >= DEBUG) + + } + + public static void error(String message) + { + if (initLogger()) { - Cache.log.debug(message); + log.error(message, null); } else { - Cache.log.trace(message); + System.err.println(message); } - return true; + } - public static void trace(String message) + public static void error(String message, Throwable t) { - println(TRACE, message); + if (initLogger()) + { + log.error(message, t); + } + else + { + System.err.println(message); + t.printStackTrace(System.err); + } + } - public static void debug(String message) + public static void fatal(String message) { - println(DEBUG, message); + if (initLogger()) + { + log.fatal(message, null); + } + else + { + System.err.println(message); + } + } - public static void info(String message) + public static void fatal(String message, Throwable t) { - println(INFO, message); + if (initLogger()) + { + log.fatal(message, t); + } + else + { + System.err.println(message); + t.printStackTrace(System.err); + } + } - public static void warn(String message) + public static boolean isDebugEnabled() { - println(WARN, message); + return log == null ? false : log.isDebugEnabled(); } - public static void error(String message) + public static boolean isTraceEnabled() { - println(ERROR, message); + return log == null ? false : log.isTraceEnabled(); } /** diff --git a/src/jalview/bin/Jalview.java b/src/jalview/bin/Jalview.java index 1ae1014..920c86d 100755 --- a/src/jalview/bin/Jalview.java +++ b/src/jalview/bin/Jalview.java @@ -20,8 +20,6 @@ */ package jalview.bin; -import java.util.Locale; - import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; @@ -39,6 +37,7 @@ import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Vector; import java.util.logging.ConsoleHandler; @@ -285,6 +284,17 @@ public class Jalview System.out.println("Launcher version: " + val); } + try + { + Cache.initLogger(); + } catch (NoClassDefFoundError error) + { + error.printStackTrace(); + System.out.println("\nEssential logging libraries not found." + + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview"); + System.exit(0); + } + // report Jalview version Cache.loadBuildProperties(true); @@ -366,16 +376,6 @@ public class Jalview } System.setProperty("http.agent", "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown")); - try - { - Cache.initLogger(); - } catch (NoClassDefFoundError error) - { - error.printStackTrace(); - System.out.println("\nEssential logging libraries not found." - + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview"); - System.exit(0); - } desktop = null; @@ -402,13 +402,13 @@ public class Jalview JalviewTaskbar.setTaskbar(this); } catch (Exception e) { - Cache.log.info("Cannot set Taskbar"); - Cache.log.error(e.getMessage()); + Cache.info("Cannot set Taskbar"); + Cache.error(e.getMessage()); // e.printStackTrace(); } catch (Throwable t) { - Cache.log.info("Cannot set Taskbar"); - Cache.log.error(t.getMessage()); + Cache.info("Cannot set Taskbar"); + Cache.error(t.getMessage()); // t.printStackTrace(); } @@ -444,7 +444,7 @@ public class Jalview { // Start the desktop questionnaire prompter with the specified // questionnaire - Cache.log.debug("Starting questionnaire url at " + url); + Cache.debug("Starting questionnaire url at " + url); desktop.checkForQuestionnaire(url); System.out.println("CMD questionnaire[-" + url + "] executed successfully!"); @@ -459,7 +459,7 @@ public class Jalview // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl"; // // String defurl = "https://www.jalview.org/cgi-bin/questionnaire.pl"; - Cache.log.debug( + Cache.debug( "Starting questionnaire with default url: " + defurl); desktop.checkForQuestionnaire(defurl); } @@ -787,12 +787,11 @@ public class Jalview * @j2sIgnore */ { - file = jalview.bin.Cache.getDefault("STARTUP_FILE", - jalview.bin.Cache.getDefault("www.jalview.org", - "https://www.jalview.org") + file = Cache.getDefault("STARTUP_FILE", + Cache.getDefault("www.jalview.org", "https://www.jalview.org") + "/examples/exampleFile_2_7.jvp"); - if (file.equals( - "http://www.jalview.org/examples/exampleFile_2_3.jar") || file.equals( + if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar") + || file.equals( "http://www.jalview.org/examples/exampleFile_2_7.jar")) { file.replace("http:", "https:"); @@ -875,62 +874,62 @@ public class Jalview lafSet = setCrossPlatformLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "system": lafSet = setSystemLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "gtk": lafSet = setGtkLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "metal": lafSet = setMetalLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "nimbus": lafSet = setNimbusLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "quaqua": lafSet = setQuaquaLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "vaqua": lafSet = setVaquaLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "mac": lafSet = setMacLookAndFeel(); if (!lafSet) { - Cache.log.error("Could not set requested laf=" + laf); + Cache.error("Could not set requested laf=" + laf); } break; case "none": break; default: - Cache.log.error("Requested laf=" + laf + " not implemented"); + Cache.error("Requested laf=" + laf + " not implemented"); } if (!lafSet) { @@ -956,9 +955,9 @@ public class Jalview set = true; } catch (Exception ex) { - Cache.log.error("Unexpected Look and Feel Exception"); - Cache.log.error(ex.getMessage()); - Cache.log.debug(Cache.getStackTraceString(ex)); + Cache.error("Unexpected Look and Feel Exception"); + Cache.error(ex.getMessage()); + Cache.debug(Cache.getStackTraceString(ex)); } return set; } @@ -972,9 +971,9 @@ public class Jalview set = true; } catch (Exception ex) { - Cache.log.error("Unexpected Look and Feel Exception"); - Cache.log.error(ex.getMessage()); - Cache.log.debug(Cache.getStackTraceString(ex)); + Cache.error("Unexpected Look and Feel Exception"); + Cache.error(ex.getMessage()); + Cache.debug(Cache.getStackTraceString(ex)); } return set; } @@ -990,7 +989,8 @@ public class Jalview if (info.getName() != null && nameStartsWith ? info.getName().toLowerCase(Locale.ROOT) .startsWith(name.toLowerCase(Locale.ROOT)) - : info.getName().toLowerCase(Locale.ROOT).equals(name.toLowerCase(Locale.ROOT))) + : info.getName().toLowerCase(Locale.ROOT) + .equals(name.toLowerCase(Locale.ROOT))) { className = info.getClassName(); break; @@ -1000,9 +1000,9 @@ public class Jalview set = true; } catch (Exception ex) { - Cache.log.error("Unexpected Look and Feel Exception"); - Cache.log.error(ex.getMessage()); - Cache.log.debug(Cache.getStackTraceString(ex)); + Cache.error("Unexpected Look and Feel Exception"); + Cache.error(ex.getMessage()); + Cache.debug(Cache.getStackTraceString(ex)); } return set; } @@ -1112,17 +1112,16 @@ public class Jalview @Override public void run() { - Cache.log.debug( - "Initialising googletracker for usage stats."); + Cache.debug("Initialising googletracker for usage stats."); Cache.initGoogleTracker(); - Cache.log.debug("Tracking enabled."); + Cache.debug("Tracking enabled."); } }, new Runnable() { @Override public void run() { - Cache.log.debug("Not enabling Google Tracking."); + Cache.debug("Not enabling Google Tracking."); } }, null, true); desktop.addDialogThread(prompter); diff --git a/src/jalview/ext/ensembl/EnsemblLookup.java b/src/jalview/ext/ensembl/EnsemblLookup.java index 9b56d6b..2507e87 100644 --- a/src/jalview/ext/ensembl/EnsemblLookup.java +++ b/src/jalview/ext/ensembl/EnsemblLookup.java @@ -276,7 +276,7 @@ public class EnsemblLookup extends EnsemblRestClient chromosome, map); } catch (NullPointerException | NumberFormatException e) { - Cache.log.error("Error looking up gene loci: " + e.getMessage()); + Cache.error("Error looking up gene loci: " + e.getMessage()); e.printStackTrace(); } return null; diff --git a/src/jalview/ext/ensembl/EnsemblSeqProxy.java b/src/jalview/ext/ensembl/EnsemblSeqProxy.java index fd8800f..82ebc4b 100644 --- a/src/jalview/ext/ensembl/EnsemblSeqProxy.java +++ b/src/jalview/ext/ensembl/EnsemblSeqProxy.java @@ -312,7 +312,7 @@ public abstract class EnsemblSeqProxy extends EnsemblRestClient if (upx.size() > 1) { - Cache.log.warn( + Cache.warn( "Implementation issue - multiple uniprot acc on product sequence."); } } diff --git a/src/jalview/ext/htsjdk/VCFReader.java b/src/jalview/ext/htsjdk/VCFReader.java index 16ff41b..508d609 100644 --- a/src/jalview/ext/htsjdk/VCFReader.java +++ b/src/jalview/ext/htsjdk/VCFReader.java @@ -85,7 +85,7 @@ public class VCFReader implements Closeable, Iterable } else { - Cache.log.error("File not found: " + filePath); + Cache.error("File not found: " + filePath); } } diff --git a/src/jalview/ext/jmol/JalviewJmolBinding.java b/src/jalview/ext/jmol/JalviewJmolBinding.java index 903d9b7..f133f20 100644 --- a/src/jalview/ext/jmol/JalviewJmolBinding.java +++ b/src/jalview/ext/jmol/JalviewJmolBinding.java @@ -122,9 +122,9 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel private String jmolScript(String script) { - Cache.log.debug(">>Jmol>> " + script); + Cache.debug(">>Jmol>> " + script); String s = jmolViewer.evalStringQuiet(script); // scriptWait(script); BH - Cache.log.debug("< 0) { - Cache.log.info("PyMOL XMLRPC started on port " + pymolXmlRpcPort); + Cache.info("PyMOL XMLRPC started on port " + pymolXmlRpcPort); } else { error += "Failed to read PyMOL XMLRPC port number"; - Cache.log.error(error); + Cache.error(error); pymolProcess.destroy(); pymolProcess = null; } @@ -300,7 +300,7 @@ public class PymolManager } } catch (Exception e) { - Cache.log.error("Failed to get REST port number from " + responses + Cache.error("Failed to get REST port number from " + responses + ": " + e.getMessage()); // logger.error("Failed to get REST port number from " + responses + ": " // + e.getMessage()); @@ -315,10 +315,10 @@ public class PymolManager } if (port == 0) { - Cache.log.error("Failed to start PyMOL with XMLRPC, response was: " + Cache.error("Failed to start PyMOL with XMLRPC, response was: " + responses); } - Cache.log.error("PyMOL started with XMLRPC on port " + port); + Cache.error("PyMOL started with XMLRPC on port " + port); return port; } diff --git a/src/jalview/ext/rbvi/chimera/JalviewChimeraBinding.java b/src/jalview/ext/rbvi/chimera/JalviewChimeraBinding.java index 7169fa2..d2c991f 100644 --- a/src/jalview/ext/rbvi/chimera/JalviewChimeraBinding.java +++ b/src/jalview/ext/rbvi/chimera/JalviewChimeraBinding.java @@ -337,16 +337,16 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel if (getResponse) { reply = lastReply; - if (Cache.log.isDebugEnabled()) { - Cache.log.debug( + if (Cache.isDebugEnabled()) { + Cache.debug( "Response from command ('" + cmd + "') was:\n" + lastReply); } } else { - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug("Command executed: " + cmd); + Cache.debug("Command executed: " + cmd); } } @@ -527,7 +527,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel atomSpecs.add(spec); } catch (IllegalArgumentException e) { - Cache.log.error("Failed to parse atomspec: " + atomSpec); + Cache.error("Failed to parse atomspec: " + atomSpec); } } return atomSpecs; @@ -679,7 +679,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel spec = parseAtomSpec(atomSpec); } catch (IllegalArgumentException e) { - Cache.log.error("Problem parsing atomspec " + atomSpec); + Cache.error("Problem parsing atomspec " + atomSpec); continue; } diff --git a/src/jalview/ext/so/SequenceOntology.java b/src/jalview/ext/so/SequenceOntology.java index 138aa58..14969fe 100644 --- a/src/jalview/ext/so/SequenceOntology.java +++ b/src/jalview/ext/so/SequenceOntology.java @@ -115,7 +115,7 @@ public class SequenceOntology implements SequenceOntologyI } } long elapsed = System.currentTimeMillis() - now; - Cache.log.info("Loaded Sequence Ontology from " + zipFile + " (" + Cache.info("Loaded Sequence Ontology from " + zipFile + " (" + elapsed + "ms)"); } catch (Exception e) { @@ -184,19 +184,19 @@ public class SequenceOntology implements SequenceOntologyI boolean oldTermIsObsolete = isObsolete(replaced); if (newTermIsObsolete && !oldTermIsObsolete) { - Cache.log.debug("Ignoring " + term.getName() + Cache.debug("Ignoring " + term.getName() + " as obsolete and duplicated by " + replaced.getName()); term = replaced; } else if (!newTermIsObsolete && oldTermIsObsolete) { - Cache.log.debug("Ignoring " + replaced.getName() + Cache.debug("Ignoring " + replaced.getName() + " as obsolete and duplicated by " + term.getName()); } else { - Cache.log.debug("Warning: " + term.getName() + Cache.debug("Warning: " + term.getName() + " has replaced " + replaced.getName() + " for lookup of '" + description + "'"); } @@ -337,7 +337,7 @@ public class SequenceOntology implements SequenceOntologyI { if (!termsNotFound.contains(term)) { - Cache.log.error("SO term " + term + " invalid"); + Cache.error("SO term " + term + " invalid"); termsNotFound.add(term); } } diff --git a/src/jalview/fts/core/GFTSPanel.java b/src/jalview/fts/core/GFTSPanel.java index ebf9ec5..da43bea 100644 --- a/src/jalview/fts/core/GFTSPanel.java +++ b/src/jalview/fts/core/GFTSPanel.java @@ -385,7 +385,7 @@ public abstract class GFTSPanel extends JPanel implements GFTSPanelI @Override public void actionPerformed(ActionEvent e) { - jalview.bin.Cache.setProperty(getAutosearchPreference(), + Cache.setProperty(getAutosearchPreference(), Boolean.toString(btn_autosearch.isSelected())); } }); diff --git a/src/jalview/fts/service/alphafold/AlphafoldRestClient.java b/src/jalview/fts/service/alphafold/AlphafoldRestClient.java index 6b855fc..0778fc3 100644 --- a/src/jalview/fts/service/alphafold/AlphafoldRestClient.java +++ b/src/jalview/fts/service/alphafold/AlphafoldRestClient.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import jalview.bin.Cache; import jalview.datamodel.DBRefEntry; import jalview.datamodel.DBRefSource; import jalview.datamodel.SequenceI; @@ -56,7 +57,7 @@ public class AlphafoldRestClient } } catch (Exception mfe) { - jalview.bin.Cache.log.debug("Exception accessing urls", mfe); + Cache.debug("Exception accessing urls", mfe); continue; } int colCounter = 0; diff --git a/src/jalview/fts/service/threedbeacons/TDBeaconsFTSPanel.java b/src/jalview/fts/service/threedbeacons/TDBeaconsFTSPanel.java index 7fa6aa5..c12b7e4 100644 --- a/src/jalview/fts/service/threedbeacons/TDBeaconsFTSPanel.java +++ b/src/jalview/fts/service/threedbeacons/TDBeaconsFTSPanel.java @@ -214,7 +214,7 @@ public class TDBeaconsFTSPanel extends GFTSPanel } } catch (Exception x) { - Cache.log.warn( + Cache.warn( "Couldn't retrieve 3d-beacons model for uniprot id" + searchTerm + " : " + tdbURL, x); diff --git a/src/jalview/gui/APQHandlers.java b/src/jalview/gui/APQHandlers.java index fb9b707..4d3a3f3 100644 --- a/src/jalview/gui/APQHandlers.java +++ b/src/jalview/gui/APQHandlers.java @@ -20,6 +20,7 @@ */ package jalview.gui; +import jalview.bin.Cache; import jalview.util.MessageManager; import jalview.util.Platform; @@ -105,7 +106,7 @@ public class APQHandlers public void handleQuitRequestWith( QuitEvent e, QuitResponse r) { - boolean confirmQuit = jalview.bin.Cache + boolean confirmQuit = Cache .getDefault( jalview.gui.Desktop.CONFIRM_KEYBOARD_QUIT, true); diff --git a/src/jalview/gui/AlignFrame.java b/src/jalview/gui/AlignFrame.java index 8deff01..2838b9d 100644 --- a/src/jalview/gui/AlignFrame.java +++ b/src/jalview/gui/AlignFrame.java @@ -368,7 +368,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, // modifyPID.setEnabled(false); } - String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT", + String sortby = Cache.getDefault("SORT_ALIGNMENT", "No sort"); if (sortby.equals("Id")) @@ -411,7 +411,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, wrapMenuItem_actionPerformed(null); } - if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false)) + if (Cache.getDefault("SHOW_OVERVIEW", false)) { this.overviewMenuItem_actionPerformed(null); } @@ -1014,7 +1014,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, */ public String getVersion() { - return jalview.bin.Cache.getProperty("VERSION"); + return Cache.getProperty("VERSION"); } public FeatureRenderer getFeatureRenderer() @@ -1216,7 +1216,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, } else { - Cache.log.error(MessageManager + Cache.error(MessageManager .formatMessage("label.couldnt_save_file", new Object[] { lastFilenameSaved })); } @@ -1299,7 +1299,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, BackupFiles backupfiles = null; if (doBackup) { - Cache.log.trace( + Cache.trace( "ALIGNFRAME making backupfiles object for " + file); backupfiles = new BackupFiles(file); } @@ -1307,19 +1307,19 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, { String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file; - Cache.log.trace("ALIGNFRAME setting PrintWriter"); + Cache.trace("ALIGNFRAME setting PrintWriter"); PrintWriter out = new PrintWriter(new FileWriter(tempFilePath)); if (backupfiles != null) { - Cache.log.trace("ALIGNFRAME about to write to temp file " + Cache.trace("ALIGNFRAME about to write to temp file " + backupfiles.getTempFilePath()); } out.print(output); - Cache.log.trace("ALIGNFRAME about to close file"); + Cache.trace("ALIGNFRAME about to close file"); out.close(); - Cache.log.trace("ALIGNFRAME closed file"); + Cache.trace("ALIGNFRAME closed file"); AlignFrame.this.setTitle(file); statusBar.setText(MessageManager.formatMessage( "label.successfully_saved_to_file_in_format", @@ -1329,29 +1329,29 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, } catch (IOException e) { lastSaveSuccessful = false; - Cache.log.error( + Cache.error( "ALIGNFRAME Something happened writing the temp file"); - Cache.log.error(e.getMessage()); - Cache.log.debug(Cache.getStackTraceString(e)); + Cache.error(e.getMessage()); + Cache.debug(Cache.getStackTraceString(e)); } catch (Exception ex) { lastSaveSuccessful = false; - Cache.log.error( + Cache.error( "ALIGNFRAME Something unexpected happened writing the temp file"); - Cache.log.error(ex.getMessage()); - Cache.log.debug(Cache.getStackTraceString(ex)); + Cache.error(ex.getMessage()); + Cache.debug(Cache.getStackTraceString(ex)); } if (doBackup) { backupfiles.setWriteSuccess(lastSaveSuccessful); - Cache.log.debug("ALIGNFRAME writing temp file was " + Cache.debug("ALIGNFRAME writing temp file was " + (lastSaveSuccessful ? "" : "NOT ") + "successful"); // do the backup file roll and rename the temp file to actual file - Cache.log.trace( + Cache.trace( "ALIGNFRAME about to rollBackupsAndRenameTempFile"); lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile(); - Cache.log.debug( + Cache.debug( "ALIGNFRAME performed rollBackupsAndRenameTempFile " + (lastSaveSuccessful ? "" : "un") + "successfully"); @@ -1534,7 +1534,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, public void associatedData_actionPerformed(ActionEvent e) { final JalviewFileChooser chooser = new JalviewFileChooser( - jalview.bin.Cache.getProperty("LAST_DIRECTORY")); + Cache.getProperty("LAST_DIRECTORY")); chooser.setFileView(new JalviewFileView()); String tooltip = MessageManager .getString("label.load_jalview_annotations"); @@ -1546,7 +1546,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, public void run() { String choice = chooser.getSelectedFile().getPath(); - jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice); + Cache.setProperty("LAST_DIRECTORY", choice); loadJalviewDataFile(chooser.getSelectedFile(), null, null, null); } }); @@ -1733,7 +1733,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, { if (originalSource != viewport) { - Cache.log.warn( + Cache.warn( "Implementation worry: mismatch of viewport origin for undo"); } originalSource.updateHiddenColumns(); @@ -1773,7 +1773,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, if (originalSource != viewport) { - Cache.log.warn( + Cache.warn( "Implementation worry: mismatch of viewport origin for redo"); } originalSource.updateHiddenColumns(); @@ -4069,7 +4069,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, { // Pick the tree file JalviewFileChooser chooser = new JalviewFileChooser( - jalview.bin.Cache.getProperty("LAST_DIRECTORY")); + Cache.getProperty("LAST_DIRECTORY")); chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle( MessageManager.getString("label.select_newick_like_tree_file")); @@ -4333,7 +4333,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, } } catch (Exception e) { - Cache.log.debug( + Cache.debug( "Exception during web service menu building process.", e); } @@ -4430,7 +4430,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, showProducts.setEnabled(showp); } catch (Exception e) { - Cache.log.warn( + Cache.warn( "canShowProducts threw an exception - please report to help@jalview.org", e); return false; @@ -4471,7 +4471,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, al = dna.translateCdna(codeTable); } catch (Exception ex) { - jalview.bin.Cache.log.error( + Cache.error( "Exception during translation. Please report this !", ex); final String msg = MessageManager.getString( "label.error_when_translating_sequences_submit_bug_report"); @@ -4834,7 +4834,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, } } catch (Exception x) { - Cache.log.debug( + Cache.debug( "Exception when processing data source as T-COFFEE score file", x); tcf = null; diff --git a/src/jalview/gui/AlignViewport.java b/src/jalview/gui/AlignViewport.java index 55abea6..ea0afe1 100644 --- a/src/jalview/gui/AlignViewport.java +++ b/src/jalview/gui/AlignViewport.java @@ -123,14 +123,14 @@ public class AlignViewport extends AlignmentViewport sequenceSetID = seqsetid; viewId = viewid; // TODO remove these once 2.4.VAMSAS release finished - if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null) + if (seqsetid != null) { - Cache.log.debug( + Cache.debug( "Setting viewport's sequence set id : " + sequenceSetID); } - if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null) + if (viewId != null) { - Cache.log.debug("Setting viewport's view id : " + viewId); + Cache.debug("Setting viewport's view id : " + viewId); } init(); @@ -185,14 +185,14 @@ public class AlignViewport extends AlignmentViewport sequenceSetID = seqsetid; viewId = viewid; // TODO remove these once 2.4.VAMSAS release finished - if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null) + if (seqsetid != null) { - Cache.log.debug( + Cache.debug( "Setting viewport's sequence set id : " + sequenceSetID); } - if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null) + if (viewId != null) { - Cache.log.debug("Setting viewport's view id : " + viewId); + Cache.debug("Setting viewport's view id : " + viewId); } if (hiddenColumns != null) @@ -594,7 +594,7 @@ public class AlignViewport extends AlignmentViewport // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass()) if (needsUpdate) { - Cache.log.debug("trigger update for " + calcId); + Cache.debug("trigger update for " + calcId); } } @@ -824,7 +824,7 @@ public class AlignViewport extends AlignmentViewport try { newAlignFrame.setMaximum( - jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false)); + Cache.getDefault("SHOW_FULLSCREEN", false)); } catch (java.beans.PropertyVetoException ex) { } diff --git a/src/jalview/gui/AlignmentPanel.java b/src/jalview/gui/AlignmentPanel.java index 35b19c1..065872f 100644 --- a/src/jalview/gui/AlignmentPanel.java +++ b/src/jalview/gui/AlignmentPanel.java @@ -806,7 +806,7 @@ public class AlignmentPanel extends GAlignmentPanel implements // could not be validated and it is not clear if it is now being // called. Log warning here in case it is called and unforeseen // problems occur - Cache.log.warn( + Cache.warn( "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences"); // scroll to start of panel @@ -1464,9 +1464,9 @@ public class AlignmentPanel extends GAlignmentPanel implements } else { - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.warn("Closing alignment panel which is already closed."); + Cache.warn("Closing alignment panel which is already closed."); } } } diff --git a/src/jalview/gui/AppJmol.java b/src/jalview/gui/AppJmol.java index 217d2b1..6f483d9 100644 --- a/src/jalview/gui/AppJmol.java +++ b/src/jalview/gui/AppJmol.java @@ -309,10 +309,10 @@ public class AppJmol extends StructureViewerBase } catch (OutOfMemoryError oomerror) { new OOMWarning("When trying to open the Jmol viewer!", oomerror); - Cache.log.debug("File locations are " + filesString); + Cache.debug("File locations are " + filesString); } catch (Exception ex) { - Cache.log.error("Couldn't open Jmol viewer!", ex); + Cache.error("Couldn't open Jmol viewer!", ex); ex.printStackTrace(); return; } @@ -333,11 +333,11 @@ public class AppJmol extends StructureViewerBase { new OOMWarning("When trying to add structures to the Jmol viewer!", oomerror); - Cache.log.debug("File locations are " + filesString); + Cache.debug("File locations are " + filesString); return; } catch (Exception ex) { - Cache.log.error("Couldn't add files to Jmol viewer!", ex); + Cache.error("Couldn't add files to Jmol viewer!", ex); ex.printStackTrace(); return; } @@ -353,7 +353,7 @@ public class AppJmol extends StructureViewerBase { try { - Cache.log.debug("Waiting around for jmb notify."); + Cache.debug("Waiting around for jmb notify."); waitTotal += waitFor; // Thread.sleep() throws an exception in JS diff --git a/src/jalview/gui/AppJmolBinding.java b/src/jalview/gui/AppJmolBinding.java index 6b06e56..2699db1 100644 --- a/src/jalview/gui/AppJmolBinding.java +++ b/src/jalview/gui/AppJmolBinding.java @@ -91,7 +91,7 @@ public class AppJmolBinding extends JalviewJmolBinding jalview.util.BrowserLauncher.openURL(url); } catch (Exception e) { - Cache.log.error("Failed to launch Jmol-associated url " + url, e); + Cache.error("Failed to launch Jmol-associated url " + url, e); // TODO: 2.6 : warn user if browser was not configured. } } diff --git a/src/jalview/gui/BlogReader.java b/src/jalview/gui/BlogReader.java index 8ba3dce..916f486 100644 --- a/src/jalview/gui/BlogReader.java +++ b/src/jalview/gui/BlogReader.java @@ -199,7 +199,7 @@ public class BlogReader extends JPanel { if (parent != null) { - Cache.log.debug("News window closed."); + Cache.debug("News window closed."); jd = null; parent.showNews(false); } @@ -247,15 +247,15 @@ public class BlogReader extends JPanel public BlogReader(Desktop desktop) { - Cache.log.debug("Constructing news reader."); + Cache.debug("Constructing news reader."); parent = desktop; _channelModel = new ChannelListModel(); // Construct our jalview news channel Channel chan = new Channel(); chan.setURL( - jalview.bin.Cache.getDefault("JALVIEW_NEWS_RSS", - jalview.bin.Cache.getDefault("www.jalview.org", + Cache.getDefault("JALVIEW_NEWS_RSS", + Cache.getDefault("www.jalview.org", "https://www.jalview.org") + "/feeds/desktop/rss")); loadLastM(); @@ -277,10 +277,10 @@ public class BlogReader extends JPanel if (setvisible) { - Cache.log.debug("Will show jalview news automatically"); + Cache.debug("Will show jalview news automatically"); showNews(); } - Cache.log.debug("Completed construction of reader."); + Cache.debug("Completed construction of reader."); } @@ -340,7 +340,7 @@ public class BlogReader extends JPanel MessageManager.getString("label.news_from_jalview"), bounds.width, bounds.height); jd.frame.setModalExclusionType(ModalExclusionType.NO_EXCLUDE); - Cache.log.debug("Displaying news."); + Cache.debug("Displaying news."); jd.waitForInput(); } } @@ -367,7 +367,7 @@ public class BlogReader extends JPanel } if (chan != null && chan.getItems() != null) { - Cache.log.debug("Scanning news items: newsnew=" + newsnew + Cache.debug("Scanning news items: newsnew=" + newsnew + " and lastDate is " + lastDate); for (Item i : (List) chan.getItems()) { @@ -426,7 +426,7 @@ public class BlogReader extends JPanel { String formatted = Cache .setDateProperty("JALVIEW_NEWS_RSS_LASTMODIFIED", lastDate); - Cache.log.debug("Saved last read date as " + formatted); + Cache.debug("Saved last read date as " + formatted); } } } @@ -759,8 +759,8 @@ public class BlogReader extends JPanel { // this tests the detection of new news based on the last read date stored // in jalview properties - jalview.bin.Cache.loadProperties(null); - jalview.bin.Cache.initLogger(); + Cache.loadProperties(null); + Cache.initLogger(); // test will advance read date each time Calendar today = Calendar.getInstance(), lastread = Calendar.getInstance(); @@ -773,16 +773,16 @@ public class BlogReader extends JPanel System.out.println("Set last date to " + formattedDate); if (me.isNewsNew()) { - Cache.log.debug("There is news to read."); + Cache.debug("There is news to read."); } else { - Cache.log.debug("There is no new news."); + Cache.debug("There is no new news."); me.xf.setTitle("Testing : Last read is " + me.lastDate); me.showNews(); me.xf.toFront(); } - Cache.log.debug("Waiting for closure."); + Cache.debug("Waiting for closure."); do { try @@ -795,11 +795,11 @@ public class BlogReader extends JPanel if (me.isNewsNew()) { - Cache.log.debug("Still new news after reader displayed."); + Cache.debug("Still new news after reader displayed."); } if (lastread.getTime().before(me.lastDate)) { - Cache.log.debug("The news was read."); + Cache.debug("The news was read."); lastread.setTime(me.lastDate); } else diff --git a/src/jalview/gui/ChimeraViewFrame.java b/src/jalview/gui/ChimeraViewFrame.java index 8dd0174..8e28da7 100644 --- a/src/jalview/gui/ChimeraViewFrame.java +++ b/src/jalview/gui/ChimeraViewFrame.java @@ -441,7 +441,7 @@ public class ChimeraViewFrame extends StructureViewerBase initChimera(); } catch (Exception ex) { - Cache.log.error("Couldn't open Chimera viewer!", ex); + Cache.error("Couldn't open Chimera viewer!", ex); } } int num = -1; @@ -486,12 +486,12 @@ public class ChimeraViewFrame extends StructureViewerBase oomerror); } catch (Exception ex) { - Cache.log.error( + Cache.error( "Couldn't open " + pe.getFile() + " in Chimera viewer!", ex); } finally { - Cache.log.debug("File locations are " + files); + Cache.debug("File locations are " + files); } } } diff --git a/src/jalview/gui/Console.java b/src/jalview/gui/Console.java index 1786c0c..cb53d14 100644 --- a/src/jalview/gui/Console.java +++ b/src/jalview/gui/Console.java @@ -42,6 +42,7 @@ import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; +import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; @@ -49,13 +50,16 @@ import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; - -import org.apache.logging.log4j.Level; +import javax.swing.border.Border; +import javax.swing.text.DefaultCaret; import jalview.bin.Cache; +import jalview.log.JLoggerI.LogLevel; +import jalview.log.JLoggerLog4j; +import jalview.log.JalviewAppender; import jalview.util.ChannelProperties; -import jalview.util.Log4j; import jalview.util.MessageManager; +import jalview.util.Platform; /** * Simple Jalview Java Console. Version 1 - allows viewing of console output @@ -101,9 +105,9 @@ public class Console extends WindowAdapter private int MIN_HEIGHT = 250; - private JComboBox logLevelCombo = new JComboBox(); + private JComboBox logLevelCombo = new JComboBox(); - protected Level startingLogLevel = Level.INFO; + protected LogLevel startingLogLevel = LogLevel.INFO; public Console() { @@ -132,6 +136,36 @@ public class Console extends WindowAdapter // textArea = cpt.getTextArea(); textArea = new JTextArea(); textArea.setEditable(false); + // autoscroll + DefaultCaret caret = (DefaultCaret) textArea.getCaret(); + caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); + // toggle autoscroll by clicking on the text area + Border pausedBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, + textArea.getForeground()); + Border noBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2); + JScrollPane scrollPane = new JScrollPane(textArea); + scrollPane.setBorder(noBorder); + textArea.addMouseListener(new MouseAdapter() + { + public void mouseClicked(MouseEvent e) + { + if (e.getButton() == MouseEvent.BUTTON1) + { + if (caret.getUpdatePolicy() == DefaultCaret.ALWAYS_UPDATE) + { + caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); + scrollPane.setBorder(pausedBorder); + } + else + { + caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); + textArea.setCaretPosition(textArea.getDocument().getLength()); + scrollPane.setBorder(noBorder); + } + } + } + }); + JButton clearButton = new JButton( MessageManager.getString("action.clear")); JButton copyToClipboardButton = new JButton( @@ -168,16 +202,17 @@ public class Console extends WindowAdapter JLabel logLevelLabel = new JLabel( MessageManager.getString("label.log_level") + ":"); - // logLevelCombo.addItem(Level.ALL); - logLevelCombo.addItem(Level.TRACE); - logLevelCombo.addItem(Level.DEBUG); - logLevelCombo.addItem(Level.INFO); - logLevelCombo.addItem(Level.WARN); - // logLevelCombo.addItem(Level.ERROR); - // logLevelCombo.addItem(Level.FATAL); - // logLevelCombo.addItem(Level.OFF); + // logLevelCombo.addItem(LogLevel.ALL); + logLevelCombo.addItem(LogLevel.TRACE); + logLevelCombo.addItem(LogLevel.DEBUG); + logLevelCombo.addItem(LogLevel.INFO); + logLevelCombo.addItem(LogLevel.WARN); + // logLevelCombo.addItem(LogLevel.ERROR); + // logLevelCombo.addItem(LogLevel.FATAL); + // logLevelCombo.addItem(LogLevel.ERROR); + // logLevelCombo.addItem(LogLevel.OFF); // set startingLogLevel - startingLogLevel = Cache.log == null ? Level.INFO + startingLogLevel = Cache.log == null ? LogLevel.INFO : Cache.log.getLevel(); setChosenLogLevelCombo(); logLevelCombo.addActionListener(new ActionListener() @@ -186,8 +221,7 @@ public class Console extends WindowAdapter { if (Cache.log != null) { - Log4j.setLevel(Cache.log, - (Level) logLevelCombo.getSelectedItem()); + Cache.log.setLevel((LogLevel) logLevelCombo.getSelectedItem()); } } @@ -195,8 +229,7 @@ public class Console extends WindowAdapter // frame = cpt; frame.getContentPane().setLayout(new BorderLayout()); - frame.getContentPane().add(new JScrollPane(textArea), - BorderLayout.CENTER); + frame.getContentPane().add(scrollPane, BorderLayout.CENTER); JPanel southPanel = new JPanel(); southPanel.setLayout(new GridBagLayout()); @@ -267,20 +300,20 @@ public class Console extends WindowAdapter setChosenLogLevelCombo(startingLogLevel); } - private void setChosenLogLevelCombo(Level setLogLevel) + private void setChosenLogLevelCombo(LogLevel setLogLevel) { logLevelCombo.setSelectedItem(setLogLevel); if (!logLevelCombo.getSelectedItem().equals(setLogLevel)) { // setLogLevel not (yet) in list - if (setLogLevel != null && setLogLevel instanceof Level) + if (setLogLevel != null && setLogLevel instanceof LogLevel) { // add new item to list (might be set via .jalview_properties) boolean added = false; for (int i = 0; i < logLevelCombo.getItemCount(); i++) { - Level l = (Level) logLevelCombo.getItemAt(i); - if (l.isMoreSpecificThan(setLogLevel)) + LogLevel l = (LogLevel) logLevelCombo.getItemAt(i); + if (l.compareTo(setLogLevel) >= 0) { logLevelCombo.insertItemAt(setLogLevel, i); added = true; @@ -296,7 +329,7 @@ public class Console extends WindowAdapter } else { - logLevelCombo.setSelectedItem(Level.INFO); + logLevelCombo.setSelectedItem(LogLevel.INFO); } } } @@ -472,9 +505,17 @@ public class Console extends WindowAdapter frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT)); // desktop.add(frame); initConsole(false); - JalviewAppender jappender = new JalviewAppender(); - JalviewAppender.setTextArea(textArea); - Log4j.addAppenderToRootLogger(jappender); + LogLevel level = (LogLevel) logLevelCombo.getSelectedItem(); + if (!Platform.isJS()) + { + JalviewAppender jappender = new JalviewAppender(level); + JalviewAppender.setTextArea(textArea); + jappender.start(); + if (Cache.log != null && Cache.log instanceof JLoggerLog4j) + { + JLoggerLog4j.addAppender(Cache.log, jappender); + } + } } public synchronized void stopConsole() @@ -817,7 +858,7 @@ public class Console extends WindowAdapter // reset log level to what it was before if (Cache.log != null) { - Log4j.setLevel(Cache.log, startingLogLevel); + Cache.log.setLevel(startingLogLevel); } unredirectStreams(); diff --git a/src/jalview/gui/CrossRefAction.java b/src/jalview/gui/CrossRefAction.java index 2ada4d2..8c64c32 100644 --- a/src/jalview/gui/CrossRefAction.java +++ b/src/jalview/gui/CrossRefAction.java @@ -229,7 +229,7 @@ public class CrossRefAction implements Runnable new OOMWarning("whilst fetching crossreferences", e); } catch (Throwable e) { - Cache.log.error("Error when finding crossreferences", e); + Cache.error("Error when finding crossreferences", e); } finally { alignFrame.setProgressBar(MessageManager.formatMessage( diff --git a/src/jalview/gui/CutAndPasteHtmlTransfer.java b/src/jalview/gui/CutAndPasteHtmlTransfer.java index fc19695..6e0032f 100644 --- a/src/jalview/gui/CutAndPasteHtmlTransfer.java +++ b/src/jalview/gui/CutAndPasteHtmlTransfer.java @@ -20,6 +20,7 @@ */ package jalview.gui; +import jalview.bin.Cache; import jalview.io.JalviewFileChooser; import jalview.io.JalviewFileView; import jalview.jbgui.GCutAndPasteHtmlTransfer; @@ -152,7 +153,7 @@ public class CutAndPasteHtmlTransfer extends GCutAndPasteHtmlTransfer // TODO: JAL-3048 JalviewFileChooser - Save option JalviewFileChooser chooser = new JalviewFileChooser( - jalview.bin.Cache.getProperty("LAST_DIRECTORY")); + Cache.getProperty("LAST_DIRECTORY")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileView(new JalviewFileView()); diff --git a/src/jalview/gui/CutAndPasteTransfer.java b/src/jalview/gui/CutAndPasteTransfer.java index 3f64ff1..5e36500 100644 --- a/src/jalview/gui/CutAndPasteTransfer.java +++ b/src/jalview/gui/CutAndPasteTransfer.java @@ -20,6 +20,7 @@ */ package jalview.gui; +import jalview.bin.Cache; import jalview.api.AlignViewportI; import jalview.api.AlignmentViewPanel; import jalview.api.ComplexAlignFile; @@ -138,7 +139,7 @@ public class CutAndPasteTransfer extends GCutAndPasteTransfer // TODO: JAL-3048 JalviewFileChooser - Save option JalviewFileChooser chooser = new JalviewFileChooser( - jalview.bin.Cache.getProperty("LAST_DIRECTORY")); + Cache.getProperty("LAST_DIRECTORY")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileView(new JalviewFileView()); @@ -327,7 +328,7 @@ public class CutAndPasteTransfer extends GCutAndPasteTransfer try { af.setMaximum( - jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false)); + Cache.getDefault("SHOW_FULLSCREEN", false)); } catch (Exception ex) { } diff --git a/src/jalview/gui/Desktop.java b/src/jalview/gui/Desktop.java index 0f80dd5..c229f9a 100644 --- a/src/jalview/gui/Desktop.java +++ b/src/jalview/gui/Desktop.java @@ -382,7 +382,7 @@ public class Desktop extends jalview.jbgui.GDesktop awtAppClassNameField.setAccessible(true); awtAppClassNameField.set(xToolkit, title); } else { - Cache.log.debug("XToolkit: awtAppClassName not found"); + Cache.debug("XToolkit: awtAppClassName not found"); } } catch (Exception e) { Cache.debug("Error setting awtAppClassName"); @@ -487,10 +487,10 @@ public class Desktop extends jalview.jbgui.GDesktop new Thread(new Runnable() { @Override public void run() { - Cache.log.debug("Filechooser init thread started."); + Cache.debug("Filechooser init thread started."); String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT"); JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat); - Cache.log.debug("Filechooser init thread finished."); + Cache.debug("Filechooser init thread finished."); } }).start(); // Add the service change listener @@ -498,7 +498,7 @@ public class Desktop extends jalview.jbgui.GDesktop @Override public void propertyChange(PropertyChangeEvent evt) { - Cache.log.debug("Firing service changed event for " + evt.getNewValue()); + Cache.debug("Firing service changed event for " + evt.getNewValue()); JalviewServicesChanged(evt); } }); @@ -566,10 +566,10 @@ public class Desktop extends jalview.jbgui.GDesktop new Thread(new Runnable() { @Override public void run() { - Cache.log.debug("Starting news thread."); + Cache.debug("Starting news thread."); jvnews = new BlogReader(me); showNews.setVisible(true); - Cache.log.debug("Completed news thread."); + Cache.debug("Completed news thread."); } }).start(); } @@ -580,11 +580,11 @@ public class Desktop extends jalview.jbgui.GDesktop new Thread(new Runnable() { @Override public void run() { - Cache.log.debug("Downloading data from identifiers.org"); + Cache.debug("Downloading data from identifiers.org"); try { UrlDownloadClient.download(IdOrgSettings.getUrl(), IdOrgSettings.getDownloadLocation()); } catch (IOException e) { - Cache.log.debug("Exception downloading identifiers.org data" + e.getMessage()); + Cache.debug("Exception downloading identifiers.org data" + e.getMessage()); } } }).start(); @@ -597,7 +597,7 @@ public class Desktop extends jalview.jbgui.GDesktop } void showNews(boolean visible) { - Cache.log.debug((visible ? "Showing" : "Hiding") + " news."); + Cache.debug((visible ? "Showing" : "Hiding") + " news."); showNews.setSelected(visible); if (visible && !jvnews.isVisible()) { new Thread(new Runnable() { @@ -643,14 +643,14 @@ public class Desktop extends jalview.jbgui.GDesktop iy = (int) (iy * sh); ih = (int) (ih * sh); while (ix >= screenSize.width) { - Cache.log.debug("Window geometry location recall error: shifting horizontal to within screenbounds."); + Cache.debug("Window geometry location recall error: shifting horizontal to within screenbounds."); ix -= screenSize.width; } while (iy >= screenSize.height) { - Cache.log.debug("Window geometry location recall error: shifting vertical to within screenbounds."); + Cache.debug("Window geometry location recall error: shifting vertical to within screenbounds."); iy -= screenSize.height; } - Cache.log.debug("Got last known dimensions for " + windowName + ": x:" + ix + " y:" + iy + " width:" + iw + Cache.debug("Got last known dimensions for " + windowName + ": x:" + ix + " y:" + iy + " width:" + iw + " height:" + ih); } // return dimensions for new instance @@ -852,7 +852,7 @@ public class Desktop extends jalview.jbgui.GDesktop frame.requestFocus(); } catch (java.beans.PropertyVetoException ve) { } catch (java.lang.ClassCastException cex) { - Cache.log.warn( + Cache.warn( "Squashed a possible GUI implementation error. If you can recreate this, please look at https://issues.jalview.org/browse/JAL-869", cex); } @@ -1140,7 +1140,7 @@ public class Desktop extends jalview.jbgui.GDesktop } private void storeLastKnownDimensions(String string, Rectangle jc) { - Cache.log.debug("Storing last known dimensions for " + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width + Cache.debug("Storing last known dimensions for " + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width + " height:" + jc.height); Cache.setProperty(string + "SCREEN_X", jc.x + ""); @@ -1275,9 +1275,9 @@ public class Desktop extends jalview.jbgui.GDesktop @Override protected void garbageCollect_actionPerformed(ActionEvent e) { // We simply collect the garbage - Cache.log.debug("Collecting garbage..."); + Cache.debug("Collecting garbage..."); System.gc(); - Cache.log.debug("Finished garbage collection."); + Cache.debug("Finished garbage collection."); } /* @@ -1441,7 +1441,7 @@ public class Desktop extends jalview.jbgui.GDesktop } catch (OutOfMemoryError oom) { new OOMWarning("Whilst saving current state to " + chosenFile.getName(), oom); } catch (Exception ex) { - Cache.log.error("Problems whilst trying to save to " + chosenFile.getName(), ex); + Cache.error("Problems whilst trying to save to " + chosenFile.getName(), ex); JvOptionPane.showMessageDialog(me, MessageManager.formatMessage("label.error_whilst_saving_current_state_to", new Object[] { chosenFile.getName() }), @@ -1496,7 +1496,7 @@ public class Desktop extends jalview.jbgui.GDesktop } catch (OutOfMemoryError oom) { new OOMWarning("Whilst loading project from " + choice, oom); } catch (Exception ex) { - Cache.log.error("Problems whilst loading project from " + choice, ex); + Cache.error("Problems whilst loading project from " + choice, ex); JvOptionPane.showMessageDialog(Desktop.desktop, MessageManager.formatMessage("label.error_whilst_loading_project_from", new Object[] { choice }), MessageManager.getString("label.couldnt_load_project"), JvOptionPane.WARNING_MESSAGE); @@ -1983,7 +1983,7 @@ public class Desktop extends jalview.jbgui.GDesktop try { openGroovyConsole(); } catch (Exception ex) { - Cache.log.error("Groovy Shell Creation failed.", ex); + Cache.error("Groovy Shell Creation failed.", ex); JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager.getString("label.couldnt_create_groovy_shell"), @@ -2294,7 +2294,7 @@ public class Desktop extends jalview.jbgui.GDesktop }); } } else { - Cache.log.error("Errors reported by JABA discovery service. Check web services preferences.\n" + ermsg); + Cache.error("Errors reported by JABA discovery service. Check web services preferences.\n" + ermsg); } } } @@ -2365,11 +2365,7 @@ public class Desktop extends jalview.jbgui.GDesktop Desktop.showUrl(url); } catch (Exception x) { if (url != null) { - if (Cache.log != null) { - Cache.log.error("Couldn't handle string " + url + " as a URL."); - } else { - System.err.println("Couldn't handle string " + url + " as a URL."); - } + Cache.error("Couldn't handle string " + url + " as a URL."); } // ignore any exceptions due to dud links. } @@ -2415,7 +2411,7 @@ public class Desktop extends jalview.jbgui.GDesktop try { SwingUtilities.invokeAndWait(prompter); } catch (Exception q) { - Cache.log.warn("Unexpected Exception in dialog thread.", q); + Cache.warn("Unexpected Exception in dialog thread.", q); } } }); @@ -2449,7 +2445,7 @@ public class Desktop extends jalview.jbgui.GDesktop @Override public void exportImage(Graphics g) throws Exception { paintAll(g); - Cache.log.info("Successfully written snapshot to file " + of.getAbsolutePath()); + Cache.info("Successfully written snapshot to file " + of.getAbsolutePath()); } }; String title = "View of desktop"; @@ -2608,7 +2604,7 @@ public class Desktop extends jalview.jbgui.GDesktop try { urlFlavour = new DataFlavor("application/x-java-url; class=java.net.URL"); } catch (ClassNotFoundException cfe) { - Cache.log.debug("Couldn't instantiate the URL dataflavor.", cfe); + Cache.debug("Couldn't instantiate the URL dataflavor.", cfe); } if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour)) { @@ -2620,7 +2616,7 @@ public class Desktop extends jalview.jbgui.GDesktop if (url != null) { protocols.add(DataSourceType.URL); files.add(url.toString()); - Cache.log.debug("Drop handled as URL dataflavor " + files.get(files.size() - 1)); + Cache.debug("Drop handled as URL dataflavor " + files.get(files.size() - 1)); return; } else { if (Platform.isAMacAndNotJS()) { @@ -2628,12 +2624,12 @@ public class Desktop extends jalview.jbgui.GDesktop } } } catch (Throwable ex) { - Cache.log.debug("URL drop handler failed.", ex); + Cache.debug("URL drop handler failed.", ex); } } if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { // Works on Windows and MacOSX - Cache.log.debug("Drop handled as javaFileListFlavor"); + Cache.debug("Drop handled as javaFileListFlavor"); for (Object file : (List) t.getTransferData(DataFlavor.javaFileListFlavor)) { files.add(file); protocols.add(DataSourceType.FILE); @@ -2643,25 +2639,25 @@ public class Desktop extends jalview.jbgui.GDesktop boolean added = false; String data = null; if (t.isDataFlavorSupported(uriListFlavor)) { - Cache.log.debug("Drop handled as uriListFlavor"); + Cache.debug("Drop handled as uriListFlavor"); // This is used by Unix drag system data = (String) t.getTransferData(uriListFlavor); } if (data == null) { // fallback to text: workaround - on OSX where there's a JVM bug - Cache.log.debug("standard URIListFlavor failed. Trying text"); + Cache.debug("standard URIListFlavor failed. Trying text"); // try text fallback DataFlavor textDf = new DataFlavor("text/plain;class=java.lang.String"); if (t.isDataFlavorSupported(textDf)) { data = (String) t.getTransferData(textDf); } - Cache.log.debug("Plain text drop content returned " + (data == null ? "Null - failed" : data)); + Cache.debug("Plain text drop content returned " + (data == null ? "Null - failed" : data)); } if (data != null) { while (protocols.size() < files.size()) { - Cache.log.debug("Adding missing FILE protocol for " + files.get(protocols.size())); + Cache.debug("Adding missing FILE protocol for " + files.get(protocols.size())); protocols.add(DataSourceType.FILE); } for (java.util.StringTokenizer st = new java.util.StringTokenizer(data, "\r\n"); st.hasMoreTokens();) { @@ -2684,28 +2680,28 @@ public class Desktop extends jalview.jbgui.GDesktop } } - if (Cache.log.isDebugEnabled()) { + if (Cache.isDebugEnabled()) { if (data == null || !added) { if (t.getTransferDataFlavors() != null && t.getTransferDataFlavors().length > 0) { - Cache.log.debug("Couldn't resolve drop data. Here are the supported flavors:"); + Cache.debug("Couldn't resolve drop data. Here are the supported flavors:"); for (DataFlavor fl : t.getTransferDataFlavors()) { - Cache.log.debug("Supported transfer dataflavor: " + fl.toString()); + Cache.debug("Supported transfer dataflavor: " + fl.toString()); Object df = t.getTransferData(fl); if (df != null) { - Cache.log.debug("Retrieves: " + df); + Cache.debug("Retrieves: " + df); } else { - Cache.log.debug("Retrieved nothing"); + Cache.debug("Retrieved nothing"); } } } else { - Cache.log.debug("Couldn't resolve dataflavor for drop: " + t.toString()); + Cache.debug("Couldn't resolve dataflavor for drop: " + t.toString()); } } } } if (Platform.isWindowsAndNotJS()) { - Cache.log.debug("Scanning dropped content for Windows Link Files"); + Cache.debug("Scanning dropped content for Windows Link Files"); // resolve any .lnk files in the file drop for (int f = 0; f < files.size(); f++) { @@ -2716,14 +2712,14 @@ public class Desktop extends jalview.jbgui.GDesktop Object obj = files.get(f); File lf = (obj instanceof File ? (File) obj : new File((String) obj)); // process link file to get a URL - Cache.log.debug("Found potential link file: " + lf); + Cache.debug("Found potential link file: " + lf); WindowsShortcut wscfile = new WindowsShortcut(lf); String fullname = wscfile.getRealFilename(); protocols.set(f, FormatAdapter.checkProtocol(fullname)); files.set(f, fullname); - Cache.log.debug("Parsed real filename " + fullname + " to extract protocol: " + protocols.get(f)); + Cache.debug("Parsed real filename " + fullname + " to extract protocol: " + protocols.get(f)); } catch (Exception ex) { - Cache.log.error("Couldn't parse " + files.get(f) + " as a link file.", ex); + Cache.error("Couldn't parse " + files.get(f) + " as a link file.", ex); } } } diff --git a/src/jalview/gui/FeatureTypeSettings.java b/src/jalview/gui/FeatureTypeSettings.java index 54eeba7..aaf81ac 100644 --- a/src/jalview/gui/FeatureTypeSettings.java +++ b/src/jalview/gui/FeatureTypeSettings.java @@ -1696,7 +1696,7 @@ public class FeatureTypeSettings extends JalviewDialog attName = (String) attCombo.getSelectedItem(); } catch (Exception e) { - Cache.log.error("Problem casting Combo box entry to String"); + Cache.error("Problem casting Combo box entry to String"); attName = attCombo.getSelectedItem().toString(); } Condition cond = (Condition) condCombo.getSelectedItem(); diff --git a/src/jalview/gui/OOMWarning.java b/src/jalview/gui/OOMWarning.java index 02c8fe1..90d5411 100644 --- a/src/jalview/gui/OOMWarning.java +++ b/src/jalview/gui/OOMWarning.java @@ -20,6 +20,7 @@ */ package jalview.gui; +import jalview.bin.Cache; import jalview.util.MessageManager; import java.awt.Component; @@ -54,16 +55,8 @@ public class OOMWarning implements Runnable desktop = instance; if (oomex != null) { - if (jalview.bin.Cache.log != null) - { - jalview.bin.Cache.log.error("Out of Memory when " + action, + Cache.error("Out of Memory when " + action, oomex); - } - else - { - System.err.println("Out of Memory when " + action); - oomex.printStackTrace(); - } } javax.swing.SwingUtilities.invokeLater(this); System.gc(); diff --git a/src/jalview/gui/PCAPanel.java b/src/jalview/gui/PCAPanel.java index 6c76c3e..25f8363 100644 --- a/src/jalview/gui/PCAPanel.java +++ b/src/jalview/gui/PCAPanel.java @@ -297,7 +297,7 @@ public class PCAPanel extends GPCAPanel // JAL-2647 disabled after load from project (until save to project done) if (getPcaModel().getInputData() == null) { - Cache.log.info( + Cache.info( "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action."); return; } diff --git a/src/jalview/gui/PopupMenu.java b/src/jalview/gui/PopupMenu.java index 7b284a9..6db9011 100644 --- a/src/jalview/gui/PopupMenu.java +++ b/src/jalview/gui/PopupMenu.java @@ -230,13 +230,13 @@ public class PopupMenu extends JPopupMenu implements ColourChangeListener urlLink = new UrlLink(link); } catch (Exception foo) { - Cache.log.error("Exception for URLLink '" + link + "'", foo); + Cache.error("Exception for URLLink '" + link + "'", foo); continue; } if (!urlLink.isValid()) { - Cache.log.error(urlLink.getInvalidMessage()); + Cache.error(urlLink.getInvalidMessage()); continue; } @@ -1165,12 +1165,12 @@ public class PopupMenu extends JPopupMenu implements ColourChangeListener urlLink = new GroupUrlLink(link); } catch (Exception foo) { - Cache.log.error("Exception for GroupURLLink '" + link + "'", foo); + Cache.error("Exception for GroupURLLink '" + link + "'", foo); continue; } if (!urlLink.isValid()) { - Cache.log.error(urlLink.getInvalidMessage()); + Cache.error(urlLink.getInvalidMessage()); continue; } final String label = urlLink.getLabel(); diff --git a/src/jalview/gui/Preferences.java b/src/jalview/gui/Preferences.java index 14063ac..a64534b 100755 --- a/src/jalview/gui/Preferences.java +++ b/src/jalview/gui/Preferences.java @@ -432,7 +432,7 @@ public class Preferences extends GPreferences } } catch (IllegalArgumentException e) { - Cache.log.error("Unknown structure viewer type: " + viewerType + Cache.error("Unknown structure viewer type: " + viewerType + ", defaulting to Jmol"); type = ViewerType.JMOL; } @@ -464,7 +464,7 @@ public class Preferences extends GPreferences } } catch (IllegalArgumentException x) { - Cache.log.error("Failed to set path - unknown viewer type",x); + Cache.error("Failed to set path - unknown viewer type",x); } } } @@ -620,7 +620,7 @@ public class Preferences extends GPreferences proxyType.setSelected(customProxy.getModel(), true); break; default: - Cache.log.warn( + Cache.warn( "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): " + proxyTypeString); } @@ -1189,7 +1189,7 @@ public class Preferences extends GPreferences if (index == -1) { // button no longer enabled if row is not selected - Cache.log.debug("Edit with no row selected in linkUrlTable"); + Cache.debug("Edit with no row selected in linkUrlTable"); return; } @@ -1241,7 +1241,7 @@ public class Preferences extends GPreferences if (index == -1) { // button no longer enabled if row is not selected - Cache.log.debug("Delete with no row selected in linkUrlTable"); + Cache.debug("Delete with no row selected in linkUrlTable"); return; } else diff --git a/src/jalview/gui/PromptUserConfig.java b/src/jalview/gui/PromptUserConfig.java index cb59452..d1fd7dd 100644 --- a/src/jalview/gui/PromptUserConfig.java +++ b/src/jalview/gui/PromptUserConfig.java @@ -89,7 +89,7 @@ public class PromptUserConfig implements Runnable * @param desktop * - where the dialog box will be shown * @param property - * - boolean property in jalview.bin.Cache + * - boolean property in Cache * @param dialogTitle * - title of prompt box * @param dialogText @@ -126,14 +126,14 @@ public class PromptUserConfig implements Runnable return; } // First - check to see if wee have an old questionnaire/response id pair. - String lastq = jalview.bin.Cache.getProperty(property); + String lastq = Cache.getProperty(property); if (lastq == null) { raiseDialog(); - Cache.log.debug("Got user response."); + Cache.debug("Got user response."); } - lastq = jalview.bin.Cache.getProperty(property); + lastq = Cache.getProperty(property); String extype = ""; Exception e = null; if (lastq == null) @@ -183,7 +183,7 @@ public class PromptUserConfig implements Runnable // report any exceptions if (e != null) { - Cache.log.warn("Unexpected exception when executing the " + extype + Cache.warn("Unexpected exception when executing the " + extype + " runnable for property " + property, e); } } @@ -193,9 +193,9 @@ public class PromptUserConfig implements Runnable */ private void raiseDialog() { - if (jalview.bin.Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - jalview.bin.Cache.log.debug("Prompting user for " + dialogTitle + Cache.debug("Prompting user for " + dialogTitle + " for Cache property " + property); } try @@ -207,36 +207,36 @@ public class PromptUserConfig implements Runnable JvOptionPane.QUESTION_MESSAGE); // and finish parsing the result - jalview.bin.Cache.log.debug("Got response : " + reply); + Cache.debug("Got response : " + reply); if (reply == JvOptionPane.YES_OPTION) { - jalview.bin.Cache.setProperty(property, "true"); + Cache.setProperty(property, "true"); } else if (reply == JvOptionPane.NO_OPTION) { if (removeifunset) { - jalview.bin.Cache.removeProperty(property); + Cache.removeProperty(property); } else { - jalview.bin.Cache.setProperty(property, "false"); + Cache.setProperty(property, "false"); } } else { - jalview.bin.Cache.log.debug("User cancelled setting " + property); + Cache.debug("User cancelled setting " + property); return; } // verify the property is set for debugging - if (jalview.bin.Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - jalview.bin.Cache.log.debug("User set property to " - + jalview.bin.Cache.getProperty(property)); + Cache.debug("User set property to " + + Cache.getProperty(property)); } } catch (Exception e) { - jalview.bin.Cache.log.warn( + Cache.warn( "Unexpected exception when prompting user for yes/no setting for property " + property, e); diff --git a/src/jalview/gui/PymolBindingModel.java b/src/jalview/gui/PymolBindingModel.java index 719ca53..ec3be0a 100644 --- a/src/jalview/gui/PymolBindingModel.java +++ b/src/jalview/gui/PymolBindingModel.java @@ -156,7 +156,7 @@ public class PymolBindingModel extends AAStructureBindingModel } else { - Cache.log.error("Failed to launch PyMOL!"); + Cache.error("Failed to launch PyMOL!"); } return pymol != null; } @@ -184,7 +184,7 @@ public class PymolBindingModel extends AAStructureBindingModel // pdbId.replace('-', 0) } catch (Exception x) { - Cache.log.error("Unxpected encoding exception for '"+pdbId+"'",x); + Cache.error("Unxpected encoding exception for '"+pdbId+"'",x); } cmd.addParameter(pdbId); diff --git a/src/jalview/gui/PymolViewer.java b/src/jalview/gui/PymolViewer.java index d7b4236..efbd155 100644 --- a/src/jalview/gui/PymolViewer.java +++ b/src/jalview/gui/PymolViewer.java @@ -210,7 +210,7 @@ public class PymolViewer extends StructureViewerBase initPymol(); } catch (Exception ex) { - Cache.log.error("Couldn't open PyMOL viewer!", ex); + Cache.error("Couldn't open PyMOL viewer!", ex); } } int num = -1; @@ -249,12 +249,12 @@ public class PymolViewer extends StructureViewerBase binding.stashFoundChains(pdb, pe.getFile()); } catch (Exception ex) { - Cache.log.error( + Cache.error( "Couldn't open " + pe.getFile() + " in Chimera viewer!", ex); } finally { - // Cache.log.debug("File locations are " + files); + // Cache.debug("File locations are " + files); } } } @@ -323,7 +323,7 @@ public class PymolViewer extends StructureViewerBase boolean opened = binding.openSession(pymolSessionFile); if (!opened) { - Cache.log.error( + Cache.error( "An error occurred opening PyMOL session file " + pymolSessionFile); } diff --git a/src/jalview/gui/RotatableCanvas.java b/src/jalview/gui/RotatableCanvas.java index 561fb3c..d7cb78a 100755 --- a/src/jalview/gui/RotatableCanvas.java +++ b/src/jalview/gui/RotatableCanvas.java @@ -508,7 +508,7 @@ public class RotatableCanvas extends JPanel implements MouseListener, } else if (evt.getKeyChar() == 's') { - // Cache.log.warn("DEBUG: Rectangle selection"); + // Cache.warn("DEBUG: Rectangle selection"); // todo not yet enabled as rectx2, recty2 are always -1 // need to set them in mouseDragged; JAL-1124 // if ((rectx2 != -1) && (recty2 != -1)) diff --git a/src/jalview/gui/SeqPanel.java b/src/jalview/gui/SeqPanel.java index 454a730..207b317 100644 --- a/src/jalview/gui/SeqPanel.java +++ b/src/jalview/gui/SeqPanel.java @@ -2802,7 +2802,7 @@ public class SeqPanel extends JPanel { if (av.getAlignment() == null) { - Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId() + Cache.warn("alignviewport av SeqSetId=" + av.getSequenceSetId() + " ViewId=" + av.getViewId() + " 's alignment is NULL! returning immediately."); return; diff --git a/src/jalview/gui/SequenceFetcher.java b/src/jalview/gui/SequenceFetcher.java index 54aefc4..9052413 100755 --- a/src/jalview/gui/SequenceFetcher.java +++ b/src/jalview/gui/SequenceFetcher.java @@ -811,7 +811,7 @@ public class SequenceFetcher extends JPanel implements Runnable } } catch (Exception e) { - Cache.log.info("Error retrieving " + accession + " from " + Cache.info("Error retrieving " + accession + " from " + proxy.getDbName(), e); } return success; diff --git a/src/jalview/gui/StructureChooser.java b/src/jalview/gui/StructureChooser.java index ce57373..34fa751 100644 --- a/src/jalview/gui/StructureChooser.java +++ b/src/jalview/gui/StructureChooser.java @@ -624,7 +624,7 @@ public class StructureChooser extends GStructureChooser // StructureChooser // works jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser( - jalview.bin.Cache.getProperty("LAST_DIRECTORY")); + Cache.getProperty("LAST_DIRECTORY")); chooser.setFileView(new jalview.io.JalviewFileView()); chooser.setDialogTitle( MessageManager.formatMessage("label.select_pdb_file_for", @@ -637,7 +637,7 @@ public class StructureChooser extends GStructureChooser if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION) { selectedPdbFileName = chooser.getSelectedFile().getPath(); - jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName); + Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName); validateSelections(); } } diff --git a/src/jalview/gui/StructureViewer.java b/src/jalview/gui/StructureViewer.java index 7b1864b..40f9ae1 100644 --- a/src/jalview/gui/StructureViewer.java +++ b/src/jalview/gui/StructureViewer.java @@ -180,7 +180,7 @@ public class StructureViewer } else { - Cache.log.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString()); + Cache.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString()); } return sview; } @@ -328,7 +328,7 @@ public class StructureViewer } else { - Cache.log.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString()); + Cache.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString()); } return sview; } @@ -366,7 +366,7 @@ public class StructureViewer viewer = new PymolViewer(viewerData, alignPanel, sessionFile, vid); break; default: - Cache.log.error(UNKNOWN_VIEWER_TYPE + type.toString()); + Cache.error(UNKNOWN_VIEWER_TYPE + type.toString()); } return viewer; } diff --git a/src/jalview/gui/StructureViewerBase.java b/src/jalview/gui/StructureViewerBase.java index ae2128b..f8fd97f 100644 --- a/src/jalview/gui/StructureViewerBase.java +++ b/src/jalview/gui/StructureViewerBase.java @@ -814,7 +814,7 @@ public abstract class StructureViewerBase extends GStructureViewer { sp.append("'" + alignPanel.getViewName() + "' "); } - Cache.log.info("Couldn't align structures with the " + sp.toString() + Cache.info("Couldn't align structures with the " + sp.toString() + "associated alignment panels.", e); } return reply; diff --git a/src/jalview/gui/TreePanel.java b/src/jalview/gui/TreePanel.java index b730df4..e88007a 100755 --- a/src/jalview/gui/TreePanel.java +++ b/src/jalview/gui/TreePanel.java @@ -30,6 +30,7 @@ import jalview.analysis.TreeModel; import jalview.analysis.scoremodels.ScoreModels; import jalview.api.analysis.ScoreModelI; import jalview.api.analysis.SimilarityParamsI; +import jalview.bin.Cache; import jalview.commands.CommandI; import jalview.commands.OrderCommand; import jalview.datamodel.Alignment; @@ -408,7 +409,7 @@ public class TreePanel extends GTreePanel { // TODO: JAL-3048 save newick file for Jalview-JS JalviewFileChooser chooser = new JalviewFileChooser( - jalview.bin.Cache.getProperty("LAST_DIRECTORY")); + Cache.getProperty("LAST_DIRECTORY")); chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle( MessageManager.getString("label.save_tree_as_newick")); @@ -419,7 +420,7 @@ public class TreePanel extends GTreePanel if (value == JalviewFileChooser.APPROVE_OPTION) { String choice = chooser.getSelectedFile().getPath(); - jalview.bin.Cache.setProperty("LAST_DIRECTORY", + Cache.setProperty("LAST_DIRECTORY", chooser.getSelectedFile().getParent()); try @@ -458,7 +459,7 @@ public class TreePanel extends GTreePanel AlignmentView originalData = tree.getOriginalData(); if (originalData == null) { - jalview.bin.Cache.log.info( + Cache.info( "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action."); return; } diff --git a/src/jalview/gui/UserQuestionnaireCheck.java b/src/jalview/gui/UserQuestionnaireCheck.java index ef86756..d2af966 100644 --- a/src/jalview/gui/UserQuestionnaireCheck.java +++ b/src/jalview/gui/UserQuestionnaireCheck.java @@ -20,6 +20,7 @@ */ package jalview.gui; +import jalview.bin.Cache; import jalview.util.MessageManager; import java.io.BufferedReader; @@ -42,7 +43,7 @@ public class UserQuestionnaireCheck implements Runnable { if (url.indexOf("questionnaire.pl") == -1) { - jalview.bin.Cache.log.error("'" + url + Cache.error("'" + url + "' is an Invalid URL for the checkForQuestionnaire() method.\n" + "This argument is only for questionnaires derived from jalview's questionnaire.pl cgi interface."); } @@ -56,7 +57,7 @@ public class UserQuestionnaireCheck implements Runnable private boolean checkresponse(URL qurl) throws Exception { - jalview.bin.Cache.log.debug("Checking Response for : " + qurl); + Cache.debug("Checking Response for : " + qurl); boolean prompt = false; // see if we have already responsed to this questionnaire or get a new // qid/rid pair @@ -101,7 +102,7 @@ public class UserQuestionnaireCheck implements Runnable try { // First - check to see if wee have an old questionnaire/response id pair. - String lastq = jalview.bin.Cache.getProperty("QUESTIONNAIRE"); + String lastq = Cache.getProperty("QUESTIONNAIRE"); if (lastq == null) { prompt = checkresponse(new URL(url @@ -133,14 +134,13 @@ public class UserQuestionnaireCheck implements Runnable if (qid != null && rid != null) { // Update our local property cache with latest qid and rid - jalview.bin.Cache.setProperty("QUESTIONNAIRE", qid + ":" + rid); + Cache.setProperty("QUESTIONNAIRE", qid + ":" + rid); } if (prompt) { String qurl = url + (url.indexOf('?') > -1 ? "&" : "?") + "qid=" + qid + "&rid=" + rid; - jalview.bin.Cache.log - .info("Prompting user for questionnaire at " + qurl); + Cache.info("Prompting user for questionnaire at " + qurl); int reply = JvOptionPane.showInternalConfirmDialog(Desktop.desktop, MessageManager.getString("label.jalview_new_questionnaire"), MessageManager.getString("label.jalview_user_survey"), @@ -148,14 +148,13 @@ public class UserQuestionnaireCheck implements Runnable if (reply == JvOptionPane.YES_OPTION) { - jalview.bin.Cache.log.debug("Opening " + qurl); + Cache.debug("Opening " + qurl); jalview.util.BrowserLauncher.openURL(qurl); } } } catch (Exception e) { - jalview.bin.Cache.log - .warn("When trying to access questionnaire URL " + url, e); + Cache.warn("When trying to access questionnaire URL " + url, e); } } diff --git a/src/jalview/gui/VamsasApplication.java b/src/jalview/gui/VamsasApplication.java index 19ede62..7881ec9 100644 --- a/src/jalview/gui/VamsasApplication.java +++ b/src/jalview/gui/VamsasApplication.java @@ -201,7 +201,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource } catch (Exception e) { - jalview.bin.Cache.log.error("Couldn't instantiate vamsas client !", + Cache.error("Couldn't instantiate vamsas client !", e); return false; } @@ -225,12 +225,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource } } catch (Error e) { - Cache.log.warn( + Cache.warn( "Probable SERIOUS VAMSAS client incompatibility - carrying on regardless", e); } catch (Exception e) { - Cache.log.warn( + Cache.warn( "Probable VAMSAS client incompatibility - carrying on regardless", e); } @@ -244,7 +244,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource private ClientHandle getJalviewHandle() { return new ClientHandle("jalview.bin.Jalview", - jalview.bin.Cache.getProperty("VERSION")); + Cache.getProperty("VERSION")); } /** @@ -271,12 +271,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource addStoreDocumentHandler(); startSession(); inInitialUpdate = true; - Cache.log.debug( + Cache.debug( "Jalview loading the Vamsas Session for the first time."); dealWithDocumentUpdate(false); // we don't push an update out to the inInitialUpdate = false; // document yet. - Cache.log.debug("... finished update for the first time."); + Cache.debug("... finished update for the first time."); } /** @@ -306,7 +306,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource } } catch (Exception e) { - Cache.log.warn( + Cache.warn( "Exception whilst refreshing jalview windows after a vamsas document update.", e); } @@ -320,10 +320,10 @@ public class VamsasApplication implements SelectionSource, VamsasSource @Override public void run() { - Cache.log.info("Jalview updating to the Vamsas Session."); + Cache.info("Jalview updating to the Vamsas Session."); dealWithDocumentUpdate(true); - Cache.log.info("Jalview finished updating to the Vamsas Session."); + Cache.info("Jalview finished updating to the Vamsas Session."); } }); @@ -353,7 +353,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource { throw new Error("Jalview not connected to Vamsas session"); } - Cache.log.info("Jalview disconnecting from the Vamsas Session."); + Cache.info("Jalview disconnecting from the Vamsas Session."); try { if (joinedSession) @@ -361,12 +361,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource boolean ourprompt = this.promptUser; this.promptUser = promptUser; vclient.finalizeClient(); - Cache.log.info("Jalview has left the session."); + Cache.info("Jalview has left the session."); this.promptUser = ourprompt; // restore default value } else { - Cache.log.warn( + Cache.warn( "JV Client leaving a session that's its not joined yet."); } joinedSession = false; @@ -377,13 +377,13 @@ public class VamsasApplication implements SelectionSource, VamsasSource vobj2jv = null; } catch (Exception e) { - Cache.log.error("Vamsas Session finalization threw exceptions!", e); + Cache.error("Vamsas Session finalization threw exceptions!", e); } } public void updateJalview(IClientDocument cdoc) { - Cache.log.debug("Jalview updating from sesion document .."); + Cache.debug("Jalview updating from sesion document .."); ensureJvVamsas(); VamsasAppDatastore vds = new VamsasAppDatastore(cdoc, vobj2jv, jv2vobj, baseProvEntry(), alRedoState); @@ -392,7 +392,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource vds.updateToJalview(); } catch (Exception e) { - Cache.log.error("Failed to update Jalview from vamsas document.", e); + Cache.error("Failed to update Jalview from vamsas document.", e); } try { @@ -404,10 +404,10 @@ public class VamsasApplication implements SelectionSource, VamsasSource } } catch (Exception e) { - Cache.log.error( + Cache.error( "Exception when updating Jalview settings from Appdata.", e); } - Cache.log.debug(".. finished updating from sesion document."); + Cache.debug(".. finished updating from sesion document."); } @@ -481,7 +481,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource } catch (Exception e) { errorsDuringUpdate = true; - Cache.log.error("Exception synchronizing " + af.getTitle() + Cache.error("Exception synchronizing " + af.getTitle() + " " + (af.getViewport().getViewName() == null ? "" : " view " + af.getViewport().getViewName()) @@ -519,7 +519,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource } } catch (Exception e) { - Cache.log.error("Exception synchronizing Views to Document :", e); + Cache.error("Exception synchronizing Views to Document :", e); errorsDuringUpdate = true; } @@ -536,7 +536,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource } } catch (Exception e) { - Cache.log.error("Client Appdata Write exception", e); + Cache.error("Client Appdata Write exception", e); errorsDuringAppUpdate = true; } vds.clearSkipList(); @@ -564,32 +564,32 @@ public class VamsasApplication implements SelectionSource, VamsasSource { int storedviews = 0; // called by update handler for document update. - Cache.log.debug("Updating jalview from changed vamsas document."); + Cache.debug("Updating jalview from changed vamsas document."); disableGui(true); try { long time = System.currentTimeMillis(); IClientDocument cdoc = vclient.getClientDocument(); - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug("Time taken to get ClientDocument = " + Cache.debug("Time taken to get ClientDocument = " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); } if (fromJalview) { storedviews += updateVamsasDocument(cdoc); - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Time taken to update Vamsas Document from jalview\t= " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); } cdoc.setVamsasRoots(cdoc.getVamsasRoots()); - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug("Time taken to set Document Roots\t\t= " + Cache.debug("Time taken to set Document Roots\t\t= " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); } @@ -597,9 +597,9 @@ public class VamsasApplication implements SelectionSource, VamsasSource else { updateJalview(cdoc); - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Time taken to update Jalview from vamsas document Roots\t= " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); @@ -607,9 +607,9 @@ public class VamsasApplication implements SelectionSource, VamsasSource } vclient.updateDocument(cdoc); - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug("Time taken to update Session Document\t= " + Cache.debug("Time taken to update Session Document\t= " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); } @@ -623,7 +623,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource recover_objectMappingBackup(); storedviews = 0; } - Cache.log.debug("Finished updating from document change."); + Cache.debug("Finished updating from document change."); disableGui(false); return storedviews; } @@ -636,12 +636,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource @Override public void propertyChange(PropertyChangeEvent evt) { - Cache.log.debug("Dealing with document update event."); + Cache.debug("Dealing with document update event."); client.dealWithDocumentUpdate(false); - Cache.log.debug("finished dealing with event."); + Cache.debug("finished dealing with event."); } }); - Cache.log.debug("Added Jalview handler for vamsas document updates."); + Cache.debug("Added Jalview handler for vamsas document updates."); } private void addStoreDocumentHandler() @@ -656,7 +656,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource { if (client.promptUser) { - Cache.log.debug( + Cache.debug( "Asking user if the vamsas session should be stored."); int reply = JvOptionPane.showInternalConfirmDialog( Desktop.desktop, @@ -667,22 +667,21 @@ public class VamsasApplication implements SelectionSource, VamsasSource if (reply == JvOptionPane.YES_OPTION) { - Cache.log.debug("Prompting for vamsas store filename."); + Cache.debug("Prompting for vamsas store filename."); Desktop.instance.vamsasSave_actionPerformed(null); - Cache.log - .debug("Finished attempt at storing document."); + Cache.debug("Finished attempt at storing document."); } - Cache.log.debug( + Cache.debug( "finished dealing with REQUESTTOCLOSE event."); } else { - Cache.log.debug( + Cache.debug( "Ignoring store document request (promptUser==false)"); } } }); - Cache.log.debug("Added Jalview handler for vamsas document updates."); + Cache.debug("Added Jalview handler for vamsas document updates."); } public void disableGui(boolean b) @@ -756,7 +755,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource } catch (Exception e) { // Complain to GUI - Cache.log.error("Failed to join vamsas session.", e); + Cache.error("Failed to join vamsas session.", e); vclient = null; } try @@ -785,16 +784,16 @@ public class VamsasApplication implements SelectionSource, VamsasSource { return; } - // if (Cache.log.isDebugEnabled()) + // if (Cache.isDebugEnabled()) // { - // Cache.log.debug("Received MouseOverMessage "+mm.getVorbaID()+" + // Cache.debug("Received MouseOverMessage "+mm.getVorbaID()+" // "+mm.getPosition()); // } Object jvobj = vobj2jv.get(mm.getVorbaID()); if (jvobj != null && jvobj instanceof SequenceI) { last = mstring; - // Cache.log.debug("Handling Mouse over "+mm.getVorbaID()+" + // Cache.debug("Handling Mouse over "+mm.getVorbaID()+" // bound to "+jvobj+" at "+mm.getPosition()); // position is character position in aligned sequence ssm.mouseOverVamsasSequence((SequenceI) jvobj, @@ -980,7 +979,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource if (v != null) { // this should really be a trace message. - // Cache.log.debug("Mouse over " + v.getId() + " bound to " + // Cache.debug("Mouse over " + v.getId() + " bound to " // + seq + " at " + index); last = seq; i = index; @@ -1001,7 +1000,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource { if (vobj2jv == null) { - Cache.log.warn( + Cache.warn( "Selection listener still active for dead session."); // not in a session. return; @@ -1101,7 +1100,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource if (sm != null) { sm.validate(); // debug - Cache.log.debug("Selection Message\n" + sm.getRawMessage()); + Cache.debug("Selection Message\n" + sm.getRawMessage()); pm.sendMessage(sm); } } @@ -1112,7 +1111,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource ssm.addSelectionListener(selecter); } catch (Exception e) { - Cache.log.error("Failed to init Vamsas Picking", e); + Cache.error("Failed to init Vamsas Picking", e); } } } diff --git a/src/jalview/gui/WsJobParameters.java b/src/jalview/gui/WsJobParameters.java index 7a139e2..1c86fec 100644 --- a/src/jalview/gui/WsJobParameters.java +++ b/src/jalview/gui/WsJobParameters.java @@ -1339,9 +1339,9 @@ public class WsJobParameters extends JPanel implements ItemListener, if (e.getSource() == setName && e.getStateChange() == e.SELECTED) { final String setname = (String) setName.getSelectedItem(); - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug("Item state changed for " + setname + Cache.debug("Item state changed for " + setname + " (handling ? " + !settingDialog + ")"); } if (settingDialog) diff --git a/src/jalview/gui/WsParamSetManager.java b/src/jalview/gui/WsParamSetManager.java index bb5d996..4c76714 100644 --- a/src/jalview/gui/WsParamSetManager.java +++ b/src/jalview/gui/WsParamSetManager.java @@ -106,7 +106,7 @@ public class WsParamSetManager implements ParamManager } } catch (IOException e) { - Cache.log.info("Failed to parse parameter file " + pfile + Cache.info("Failed to parse parameter file " + pfile + " (Check that all JALVIEW_WSPARAMFILES entries are valid!)", e); } @@ -171,7 +171,7 @@ public class WsParamSetManager implements ParamManager { if (filename != null && !((outfile = new File(filename)).canWrite())) { - Cache.log.warn("Can't write to " + filename + Cache.warn("Can't write to " + filename + " - Prompting for new file to write to."); filename = null; } @@ -218,7 +218,7 @@ public class WsParamSetManager implements ParamManager } if (outfile != null) { - String paramFiles = jalview.bin.Cache.getDefault("WS_PARAM_FILES", + String paramFiles = Cache.getDefault("WS_PARAM_FILES", filename); if (paramFiles.indexOf(filename) == -1) { @@ -255,14 +255,14 @@ public class WsParamSetManager implements ParamManager parameterSet.setSourceFile(filename); } catch (Exception e) { - Cache.log.error("Couldn't write parameter file to " + outfile, e); + Cache.error("Couldn't write parameter file to " + outfile, e); } } } /* * - * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache + * JalviewFileChooser chooser = new JalviewFileChooser(Cache * .getProperty("LAST_DIRECTORY"), new String[] { "jc" }, new String[] { * "Jalview User Colours" }, "Jalview User Colours"); chooser.setFileView(new * jalview.io.JalviewFileView()); @@ -272,8 +272,8 @@ public class WsParamSetManager implements ParamManager * int value = chooser.showOpenDialog(this); * * if (value == JalviewFileChooser.APPROVE_OPTION) { File choice = - * chooser.getSelectedFile(); jalview.bin.Cache.setProperty("LAST_DIRECTORY", - * choice.getParent()); String defaultColours = jalview.bin.Cache.getDefault( + * chooser.getSelectedFile(); Cache.setProperty("LAST_DIRECTORY", + * choice.getParent()); String defaultColours = Cache.getDefault( * "USER_DEFINED_COLOURS", choice.getPath()); if * (defaultColours.indexOf(choice.getPath()) == -1) { defaultColours = * defaultColours.concat("|") .concat(choice.getPath()); } (non-Javadoc) @@ -290,7 +290,7 @@ public class WsParamSetManager implements ParamManager { return; } - String paramFiles = jalview.bin.Cache.getDefault("WS_PARAM_FILES", ""); + String paramFiles = Cache.getDefault("WS_PARAM_FILES", ""); if (paramFiles.indexOf(filename) > -1) { String nparamFiles = new String(); @@ -303,7 +303,7 @@ public class WsParamSetManager implements ParamManager nparamFiles = nparamFiles.concat("|").concat(fl); } } - jalview.bin.Cache.setProperty("WS_PARAM_FILES", nparamFiles); + Cache.setProperty("WS_PARAM_FILES", nparamFiles); } try @@ -320,7 +320,7 @@ public class WsParamSetManager implements ParamManager } } catch (Exception e) { - Cache.log.error( + Cache.error( "Exception when trying to delete webservice user preset: ", e); } diff --git a/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java b/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java index f2d6b96..b1ad65f 100644 --- a/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java +++ b/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java @@ -420,7 +420,7 @@ public class ThreeDBStructureChooserQuerySource pdbEntry.setType(PDBEntry.Type.valueOf(strucFormat)); } catch (Exception q) { - Cache.log.warn("Unknown filetype for 3D Beacons Model from: " + Cache.warn("Unknown filetype for 3D Beacons Model from: " + strucFormat + " - " + pdbIdStr + " - " + modelPage); } diff --git a/src/jalview/io/BackupFilesPresetEntry.java b/src/jalview/io/BackupFilesPresetEntry.java index ff8a5e6..13509ee 100644 --- a/src/jalview/io/BackupFilesPresetEntry.java +++ b/src/jalview/io/BackupFilesPresetEntry.java @@ -124,7 +124,7 @@ public class BackupFilesPresetEntry confirmDelete = Boolean.valueOf(st.nextToken()); } catch (Exception e) { - Cache.log.error("Error parsing backupfiles scheme '" + line + "'"); + Cache.error("Error parsing backupfiles scheme '" + line + "'"); } return new BackupFilesPresetEntry(suffix, digits, reverse, keepAll, diff --git a/src/jalview/io/BioJsHTMLOutput.java b/src/jalview/io/BioJsHTMLOutput.java index 9db3df2..48988cf 100644 --- a/src/jalview/io/BioJsHTMLOutput.java +++ b/src/jalview/io/BioJsHTMLOutput.java @@ -20,6 +20,7 @@ */ package jalview.io; +import jalview.bin.Cache; import jalview.gui.AlignmentPanel; import jalview.gui.OOMWarning; import jalview.json.binding.biojs.BioJSReleasePojo; @@ -47,10 +48,10 @@ public class BioJsHTMLOutput extends HTMLOutput public static final String DEFAULT_DIR = System.getProperty("user.home") + File.separatorChar + ".biojs_templates" + File.separatorChar; - public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = jalview.bin.Cache + public static final String BJS_TEMPLATES_LOCAL_DIRECTORY = Cache .getDefault("biojs_template_directory", DEFAULT_DIR); - public static final String BJS_TEMPLATE_GIT_REPO = jalview.bin.Cache + public static final String BJS_TEMPLATE_GIT_REPO = Cache .getDefault("biojs_template_git_repo", "https://raw.githubusercontent.com/jalview/exporter-templates/master/biojs/package.json"); diff --git a/src/jalview/io/EMBLLikeFlatFile.java b/src/jalview/io/EMBLLikeFlatFile.java index 64943b2..9e8cff6 100644 --- a/src/jalview/io/EMBLLikeFlatFile.java +++ b/src/jalview/io/EMBLLikeFlatFile.java @@ -291,7 +291,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile int slashPos = line.indexOf('/'); if (slashPos == -1) { - Cache.log.error("Unexpected EMBL line ignored: " + line); + Cache.error("Unexpected EMBL line ignored: " + line); line = nextLine(); continue; } @@ -321,7 +321,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile data.codonStart = Integer.parseInt(featureValue.trim()); } catch (NumberFormatException e) { - Cache.log.error("Invalid codon_start in XML for " + this.accession + Cache.error("Invalid codon_start in XML for " + this.accession + ": " + e.getMessage()); } } @@ -357,7 +357,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile } else { - Cache.log.error("Ignoring CDS feature with no protein_id for " + Cache.error("Ignoring CDS feature with no protein_id for " + sourceDb + ":" + accession); } @@ -382,7 +382,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile { if (this.accession == null || this.sequenceString == null) { - Cache.log.error("Failed to parse data from EMBL"); + Cache.error("Failed to parse data from EMBL"); return; } @@ -584,7 +584,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile * workaround until we handle all 'location' formats fully * e.g. X53828.1:60..1058 or <123..>289 */ - Cache.log.error(String.format( + Cache.error(String.format( "Implementation Notice: EMBLCDS location '%s'not properly supported yet" + " - Making up the CDNA region of (%s:%s)... may be incorrect", data.cdsLocation, sourceDb, this.accession)); @@ -594,12 +594,12 @@ public abstract class EMBLLikeFlatFile extends AlignFile if (peptideLength * 3 == completeCodonsLength) { // this might occur for CDS sequences where no features are marked - Cache.log.warn("Assuming no stop codon at end of cDNA fragment"); + Cache.warn("Assuming no stop codon at end of cDNA fragment"); mappedDnaEnd = dna.getEnd(); } else if ((peptideLength + 1) * 3 == completeCodonsLength) { - Cache.log.warn("Assuming stop codon at end of cDNA fragment"); + Cache.warn("Assuming stop codon at end of cDNA fragment"); mappedDnaEnd = dna.getEnd() - 3; } @@ -673,7 +673,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile return MappingUtils.rangeListToArray(ranges); } catch (ParseException e) { - Cache.log.warn( + Cache.warn( String.format("Not parsing inexact CDS location %s in ENA %s", location, accession)); return new int[] {}; @@ -718,7 +718,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile String[] tokens = line.split(WHITESPACE); if (tokens.length < 2) { - Cache.log.error("Ignoring bad EMBL line for " + this.accession + Cache.error("Ignoring bad EMBL line for " + this.accession + ": " + line); break; } diff --git a/src/jalview/io/EmblFlatFile.java b/src/jalview/io/EmblFlatFile.java index 7808d1a..14dcb9a 100644 --- a/src/jalview/io/EmblFlatFile.java +++ b/src/jalview/io/EmblFlatFile.java @@ -124,7 +124,7 @@ public class EmblFlatFile extends EMBLLikeFlatFile this.length = Integer.valueOf(bits[0]); } catch (NumberFormatException e) { - Cache.log.error("bad length read in flatfile, line: " + line); + Cache.error("bad length read in flatfile, line: " + line); } } diff --git a/src/jalview/io/FileLoader.java b/src/jalview/io/FileLoader.java index c7c1d71..3d2dded 100755 --- a/src/jalview/io/FileLoader.java +++ b/src/jalview/io/FileLoader.java @@ -483,7 +483,7 @@ public class FileLoader implements Runnable try { - alignFrame.setMaximum(jalview.bin.Cache + alignFrame.setMaximum(Cache .getDefault("SHOW_FULLSCREEN", false)); } catch (java.beans.PropertyVetoException ex) { diff --git a/src/jalview/io/FileParse.java b/src/jalview/io/FileParse.java index 5fd33be..1306f43 100755 --- a/src/jalview/io/FileParse.java +++ b/src/jalview/io/FileParse.java @@ -225,7 +225,7 @@ public class FileParse { if (!input.markSupported()) { - Cache.log.error( + Cache.error( "FileParse.izGzipStream: input stream must support mark/reset"); return false; } diff --git a/src/jalview/io/FormatAdapter.java b/src/jalview/io/FormatAdapter.java index 31751f5..00920db 100755 --- a/src/jalview/io/FormatAdapter.java +++ b/src/jalview/io/FormatAdapter.java @@ -65,13 +65,13 @@ public class FormatAdapter extends AppletFormatAdapter private void init() { - if (jalview.bin.Cache.getDefault("STRUCT_FROM_PDB", true)) + if (Cache.getDefault("STRUCT_FROM_PDB", true)) { - annotFromStructure = jalview.bin.Cache.getDefault("ADD_TEMPFACT_ANN", + annotFromStructure = Cache.getDefault("ADD_TEMPFACT_ANN", true); - localSecondaryStruct = jalview.bin.Cache.getDefault("ADD_SS_ANN", + localSecondaryStruct = Cache.getDefault("ADD_SS_ANN", true); - serviceSecondaryStruct = jalview.bin.Cache.getDefault("USE_RNAVIEW", + serviceSecondaryStruct = Cache.getDefault("USE_RNAVIEW", true); } else diff --git a/src/jalview/io/HtmlSvgOutput.java b/src/jalview/io/HtmlSvgOutput.java index b8241c8..81773bc 100644 --- a/src/jalview/io/HtmlSvgOutput.java +++ b/src/jalview/io/HtmlSvgOutput.java @@ -189,7 +189,7 @@ public class HtmlSvgOutput extends HTMLOutput public boolean isEmbedData() { return Boolean.valueOf( - jalview.bin.Cache.getDefault("EXPORT_EMBBED_BIOJSON", "true")); + Cache.getDefault("EXPORT_EMBBED_BIOJSON", "true")); } @Override diff --git a/src/jalview/io/ModellerDescription.java b/src/jalview/io/ModellerDescription.java index a56f2af..d66fe6c 100755 --- a/src/jalview/io/ModellerDescription.java +++ b/src/jalview/io/ModellerDescription.java @@ -20,6 +20,7 @@ */ package jalview.io; +import jalview.bin.Cache; import jalview.datamodel.DBRefEntry; import jalview.datamodel.SequenceI; @@ -110,7 +111,7 @@ public class ModellerDescription { value = r.stringMatched(1); } - // jalview.bin.Cache.log.debug("from '" + field + "' matched '" + value + + // Cache.debug("from '" + field + "' matched '" + value + // "'"); try { @@ -165,7 +166,7 @@ public class ModellerDescription } else { - // jalview.bin.Cache.log.debug( + // Cache.debug( // "Ignoring non-Modeller description: invalid integer-like // field '" + field + "'"); type = -1; /* invalid field! - throw the FieldSet away */ diff --git a/src/jalview/io/StockholmFile.java b/src/jalview/io/StockholmFile.java index c8c9c8a..cff328b 100644 --- a/src/jalview/io/StockholmFile.java +++ b/src/jalview/io/StockholmFile.java @@ -23,8 +23,6 @@ */ package jalview.io; -import java.util.Locale; - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; @@ -33,6 +31,7 @@ import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Vector; @@ -57,8 +56,6 @@ import jalview.util.DBRefUtils; import jalview.util.Format; import jalview.util.MessageManager; -// import org.apache.log4j.*; - /** * This class is supposed to parse a Stockholm format file into Jalview There * are TODOs in this class: we do not know what the database source and version @@ -79,14 +76,15 @@ public class StockholmFile extends AlignFile { private static final String ANNOTATION = "annotation"; -// private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "("); -// -// private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")"); + // private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "("); + // + // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")"); public static final Regex DETECT_BRACKETS = new Regex( "(<|>|\\[|\\]|\\(|\\)|\\{|\\})"); - // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first. + // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using + // NOT_RNASS first. public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; // use the following regex to decide an annotations (whole) line is NOT an RNA @@ -242,8 +240,8 @@ public class StockholmFile extends AlignFile Regex openparen = new Regex("(<|\\[)", "("); Regex closeparen = new Regex("(>|\\])", ")"); -// // Detect if file is RNA by looking for bracket types -// Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))"); + // // Detect if file is RNA by looking for bracket types + // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))"); rend.optimize(); p.optimize(); @@ -339,7 +337,8 @@ public class StockholmFile extends AlignFile if (dbr != null) { // we could get very clever here - but for now - just try to - // guess accession type from type of sequence, source of alignment plus + // guess accession type from type of sequence, source of alignment + // plus // structure // of accession guessDatabaseFor(seqO, dbr, dbsource); @@ -527,8 +526,10 @@ public class StockholmFile extends AlignFile treeName = an.stringMatched(2); treeString = new StringBuffer(); } - // TODO: JAL-3532 - this is where GF comments and database references are lost - // suggest overriding this method for Stockholm files to catch and properly + // TODO: JAL-3532 - this is where GF comments and database + // references are lost + // suggest overriding this method for Stockholm files to catch and + // properly // process CC, DR etc into multivalued properties setAlignmentProperty(an.stringMatched(1), an.stringMatched(2)); } @@ -760,7 +761,8 @@ public class StockholmFile extends AlignFile } if (dbsource == null) { - // make up an origin based on whether the sequence looks like it is nucleotide + // make up an origin based on whether the sequence looks like it is + // nucleotide // or protein dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM"; } @@ -944,6 +946,7 @@ public class StockholmFile extends AlignFile return ref.getSource().toString() + " ; " + ref.getAccessionId().toString(); } + @Override public String print(SequenceI[] s, boolean jvSuffix) { diff --git a/src/jalview/io/VamsasAppDatastore.java b/src/jalview/io/VamsasAppDatastore.java index 2fc526b..6e0dab0 100644 --- a/src/jalview/io/VamsasAppDatastore.java +++ b/src/jalview/io/VamsasAppDatastore.java @@ -183,7 +183,7 @@ public class VamsasAppDatastore Vobject obj = getjv2vObj(seqsetidobj); if (obj != null && !(obj instanceof Alignment)) { - Cache.log.warn( + Cache.warn( "IMPLEMENTATION ERROR?: Unexpected mapping for unmapped jalview string object content:" + seqsetidobj + " to object " + obj); } @@ -191,16 +191,16 @@ public class VamsasAppDatastore } else { - Cache.log.warn("Unexpected mapping for Jalview String Object ID " + Cache.warn("Unexpected mapping for Jalview String Object ID " + seqsetidobj + " to another jalview dataset object " + seqsetidobj); } } } - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Returning null VorbaID binding for jalview object " + jvobj); } return null; @@ -217,7 +217,7 @@ public class VamsasAppDatastore if (id == null) { id = cdoc.registerObject(vobj); - Cache.log.debug( + Cache.debug( "Registering new object and returning null for getvObj2jv"); return null; } @@ -237,7 +237,7 @@ public class VamsasAppDatastore if (id == null || vobj.getVorbaId() == null || cdoc.getObject(id) != vobj) { - Cache.log.error("Failed to get id for " + Cache.error("Failed to get id for " + (vobj.isRegisterable() ? "registerable" : "unregisterable") + " object " + vobj); @@ -247,7 +247,7 @@ public class VamsasAppDatastore if (vobj2jv.containsKey(vobj.getVorbaId()) && !((VorbaId) vobj2jv.get(vobj.getVorbaId())).equals(jvobj)) { - Cache.log.debug( + Cache.debug( "Warning? Overwriting existing vamsas id binding for " + vobj.getVorbaId(), new Exception(MessageManager.getString( @@ -256,19 +256,19 @@ public class VamsasAppDatastore else if (jv2vobj.containsKey(jvobj) && !((VorbaId) jv2vobj.get(jvobj)).equals(vobj.getVorbaId())) { - Cache.log.debug( + Cache.debug( "Warning? Overwriting existing jalview object binding for " + jvobj, new Exception("Overwriting jalview object binding.")); } /* - * Cache.log.error("Attempt to make conflicting object binding! "+vobj+" id " + * Cache.error("Attempt to make conflicting object binding! "+vobj+" id " * +vobj.getVorbaId()+" already bound to "+getvObj2jv(vobj)+" and "+jvobj+" * already bound to "+getjv2vObj(jvobj),new Exception("Excessive call to * bindjvvobj")); } */ // we just update the hash's regardless! - Cache.log.debug("Binding " + vobj.getVorbaId() + " to " + jvobj); + Cache.debug("Binding " + vobj.getVorbaId() + " to " + jvobj); vobj2jv.put(vobj.getVorbaId(), jvobj); // JBPNote - better implementing a hybrid invertible hash. jv2vobj.put(jvobj, vobj.getVorbaId()); @@ -297,7 +297,7 @@ public class VamsasAppDatastore DataSet dataset = null; if (jds == null) { - Cache.log.warn("Creating new dataset for an alignment."); + Cache.warn("Creating new dataset for an alignment."); jal.setDataset(null); jds = jal.getDataset(); } @@ -349,7 +349,7 @@ public class VamsasAppDatastore if (dataset == null) { - Cache.log.warn("Creating new vamsas dataset for alignment view " + Cache.warn("Creating new vamsas dataset for alignment view " + av.getSequenceSetId()); // we create a new dataset on the default vamsas root. root = cdoc.getVamsasRoots()[0]; // default vamsas root for modifying. @@ -556,7 +556,7 @@ public class VamsasAppDatastore if (aa[i].groupRef != null) { // TODO: store any group associated annotation references - Cache.log.warn( + Cache.warn( "Group associated sequence annotation is not stored in VAMSAS document."); continue; } @@ -699,13 +699,13 @@ public class VamsasAppDatastore // LOCK METHODS) { // verify annotation - update (perhaps) - Cache.log.info( + Cache.info( "update alignment sequence annotation. not yet implemented."); } else { // verify annotation - update (perhaps) - Cache.log.info( + Cache.info( "updated alignment sequence annotation added."); } } @@ -889,7 +889,7 @@ public class VamsasAppDatastore } if (getjv2vObj(jvalsq.getDatasetSequence()) == null) { - Cache.log.warn( + Cache.warn( "Serious Implementation error - Unbound dataset sequence in alignment: " + jvalsq.getDatasetSequence()); } @@ -947,9 +947,9 @@ public class VamsasAppDatastore alseq.setDescription(valseq.getDescription()); modal = true; } - if (modal && Cache.log.isDebugEnabled()) + if (modal && Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Updating apparently edited sequence " + alseq.getName()); } } @@ -986,7 +986,7 @@ public class VamsasAppDatastore } else { - Cache.log.error( + Cache.error( "Invalid dataset sequence id (null) for alignment sequence " + valseq.getVorbaId()); } @@ -1332,7 +1332,7 @@ public class VamsasAppDatastore @Override public JarInputStream getJarInputStream() throws IOException { - jalview.bin.Cache.log.debug( + Cache.debug( "Returning client input stream for Jalview from Vamsas Document."); return new JarInputStream(cappdata.getClientInputStream()); } @@ -1380,7 +1380,7 @@ public class VamsasAppDatastore @Override public JarInputStream getJarInputStream() throws IOException { - jalview.bin.Cache.log.debug( + Cache.debug( "Returning user input stream for Jalview from Vamsas Document."); return new JarInputStream(cappdata.getUserInputStream()); } @@ -1426,8 +1426,7 @@ public class VamsasAppDatastore // TODO implement this : af.getNumberOfViews String seqsetidobj = av.getSequenceSetId(); views = Desktop.getViewports(seqsetidobj); - Cache.log - .debug("Found " + (views == null ? " no " : "" + views.length) + Cache.debug("Found " + (views == null ? " no " : "" + views.length) + " views for '" + av.getSequenceSetId() + "'"); if (views.length > 1) { @@ -1544,14 +1543,14 @@ public class VamsasAppDatastore } catch (Exception e) { // TODO raise GUI warning if user requests it. - jalview.bin.Cache.log.error( + Cache.error( "Couldn't update jalview client application data. Giving up - local settings probably lost.", e); } } else { - jalview.bin.Cache.log.error( + Cache.error( "Couldn't access client application data for vamsas session. This is probably a vamsas client bug."); } } @@ -1617,13 +1616,13 @@ public class VamsasAppDatastore int jremain = 0; if (jdataset == null) { - Cache.log.debug("Initialising new jalview dataset fields"); + Cache.debug("Initialising new jalview dataset fields"); newds = true; dsseqs = new Vector(); } else { - Cache.log.debug("Update jalview dataset from vamsas."); + Cache.debug("Update jalview dataset from vamsas."); jremain = jdataset.getHeight(); dsseqs = jdataset.getSequences(); } @@ -1663,7 +1662,7 @@ public class VamsasAppDatastore dsseqs.set(i, null); } jdataset = new jalview.datamodel.Alignment(seqs); - Cache.log.debug("New vamsas dataset imported into jalview."); + Cache.debug("New vamsas dataset imported into jalview."); bindjvvobj(jdataset, dataset); } // //////// @@ -1683,7 +1682,7 @@ public class VamsasAppDatastore // annotations if (dsSeq == null) { - jalview.bin.Cache.log.warn( + Cache.warn( "Couldn't resolve jalview sequenceI for dataset object reference " + ((Vobject) dataset .getDataSetAnnotations(dsa) @@ -1704,14 +1703,14 @@ public class VamsasAppDatastore // JBPNote: we could just add them to all alignments but // that may complicate cross references in the jalview // datamodel - Cache.log.warn( + Cache.warn( "Ignoring dataset annotation with annotationElements. Not yet supported in jalview."); } } } else { - Cache.log.warn( + Cache.warn( "Ignoring multiply referenced dataset sequence annotation for binding to datsaet sequence features."); } } @@ -1807,7 +1806,7 @@ public class VamsasAppDatastore // OBJECT LOCK // METHODS) { - Cache.log.info( + Cache.info( "UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation"); // TODO: should at least replace with new one - otherwise // things will break @@ -1831,7 +1830,7 @@ public class VamsasAppDatastore dsseqs.set(i, null); } jal = new jalview.datamodel.Alignment(seqs); - Cache.log.debug("New vamsas alignment imported into jalview " + Cache.debug("New vamsas alignment imported into jalview " + alignment.getVorbaId().getId()); jal.setDataset(jdataset); } @@ -1870,7 +1869,7 @@ public class VamsasAppDatastore // jan.update(getjAlignmentAnnotation(jal, an[a])); // update // from another annotation object in place. - Cache.log.debug( + Cache.debug( "update from vamsas alignment annotation to existing jalview alignment annotation."); if (an[j].getModifiable() == null) // TODO: USE VAMSAS // LIBRARY OBJECT LOCK @@ -1878,7 +1877,7 @@ public class VamsasAppDatastore { // TODO: user defined annotation is totally mutable... - so // load it up or throw away if locally edited. - Cache.log.info( + Cache.info( "NOT IMPLEMENTED - Recovering user-modifiable annotation - yet..."); } // TODO: compare annotation element rows @@ -1898,7 +1897,7 @@ public class VamsasAppDatastore AlignFrame alignFrame; if (av == null) { - Cache.log.debug("New alignframe for alignment " + Cache.debug("New alignframe for alignment " + alignment.getVorbaId()); // /////////////////////////////// // construct alignment view @@ -1924,7 +1923,7 @@ public class VamsasAppDatastore } // TODO: automatically create meaningful title for a vamsas // alignment using its provenance. - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { title = title + "(" + alignment.getVorbaId() + ")"; @@ -1971,12 +1970,12 @@ public class VamsasAppDatastore vstree.UpdateSequenceTreeMap(tp); } catch (RuntimeException e) { - Cache.log.warn("update of labels failed.", e); + Cache.warn("update of labels failed.", e); } } else { - Cache.log.warn("Cannot create tree for tree " + t + Cache.warn("Cannot create tree for tree " + t + " in document (" + alignment.getTree(t).getVorbaId()); } @@ -2073,7 +2072,7 @@ public class VamsasAppDatastore if (anot[row][pos] != null) { // only time this should happen is if the After flag is set. - Cache.log.debug("Ignoring duplicate annotation site at " + pos); + Cache.debug("Ignoring duplicate annotation site at " + pos); continue; } if (anot[1 - row][pos] != null) @@ -2109,7 +2108,7 @@ public class VamsasAppDatastore else if (glyphs[g].getDict().equals( uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO)) { - Cache.log.debug("ignoring hydrophobicity glyph marker."); + Cache.debug("ignoring hydrophobicity glyph marker."); AeContent[HASHPHOB] = true; char c = (dc = glyphs[g].getContent()).charAt(0); // dc may get overwritten - but we still set the colour. @@ -2125,7 +2124,7 @@ public class VamsasAppDatastore } else { - Cache.log.debug( + Cache.debug( "IMPLEMENTATION TODO: Ignoring unknown glyph type " + glyphs[g].getDict()); } @@ -2137,7 +2136,7 @@ public class VamsasAppDatastore AeContent[HASVALS] = true; if (ae[aa].getValueCount() > 1) { - Cache.log.warn( + Cache.warn( "ignoring additional " + (ae[aa].getValueCount() - 1) + " values in annotation element."); } @@ -2158,7 +2157,7 @@ public class VamsasAppDatastore } else { - Cache.log.warn("Ignoring out of bound annotation element " + aa + Cache.warn("Ignoring out of bound annotation element " + aa + " in " + annotation.getVorbaId().getId()); } } @@ -2249,7 +2248,7 @@ public class VamsasAppDatastore val = Float.valueOf(props[p].getContent()); } catch (Exception e) { - Cache.log.warn("Failed to parse threshold property"); + Cache.warn("Failed to parse threshold property"); } if (val != null) { @@ -2289,14 +2288,14 @@ public class VamsasAppDatastore } if (parsedRangeAnnotation == null) { - Cache.log.debug( + Cache.debug( "Inserting empty annotation row elements for a whole-alignment annotation."); } else { if (parsedRangeAnnotation[3] != null) { - Cache.log.warn("Ignoring 'After' annotation row in " + Cache.warn("Ignoring 'After' annotation row in " + annotation.getVorbaId()); } jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2]; @@ -2416,7 +2415,7 @@ public class VamsasAppDatastore } if (annotation.getLinkCount() > 0) { - Cache.log.warn("Ignoring " + annotation.getLinkCount() + Cache.warn("Ignoring " + annotation.getLinkCount() + "links added to AlignmentAnnotation."); } if (annotation.getModifiable() == null @@ -2441,7 +2440,7 @@ public class VamsasAppDatastore } } catch (Exception e) { - Cache.log.info( + Cache.info( "UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly."); } return jan; @@ -2737,7 +2736,7 @@ public class VamsasAppDatastore DataSet dataset = null; if (jal.getDataset() == null) { - Cache.log.warn("Creating new dataset for an alignment."); + Cache.warn("Creating new dataset for an alignment."); jal.setDataset(null); } dataset = (DataSet) ((Alignment) getjv2vObj( @@ -2745,7 +2744,7 @@ public class VamsasAppDatastore if (dataset == null) { dataset = (DataSet) getjv2vObj(jal.getDataset()); - Cache.log.error( + Cache.error( "Can't find the correct dataset for the alignment in this view. Creating new one."); } @@ -2770,7 +2769,7 @@ public class VamsasAppDatastore } else { - Cache.log.warn( + Cache.warn( "NO Vamsas Binding for local sequence! NOT CREATING MAPPING FOR " + dmps[smp].getDisplayId(true) + " to " + mps[smp].getTo().getName()); diff --git a/src/jalview/io/vamsas/DatastoreItem.java b/src/jalview/io/vamsas/DatastoreItem.java index a1d8380..e20f51e 100644 --- a/src/jalview/io/vamsas/DatastoreItem.java +++ b/src/jalview/io/vamsas/DatastoreItem.java @@ -25,11 +25,9 @@ import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.Vector; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import jalview.bin.Cache; import jalview.io.VamsasAppDatastore; +import jalview.log.JLoggerLog4j; import jalview.util.MessageManager; import uk.ac.vamsas.client.IClientDocument; import uk.ac.vamsas.client.Vobject; @@ -62,7 +60,8 @@ public abstract class DatastoreItem /** * shared log instance */ - protected static Logger log = LogManager.getLogger(DatastoreItem.class); + protected static JLoggerLog4j log = JLoggerLog4j + .getLogger(DatastoreItem.class.getCanonicalName()); /** * note: this is taken verbatim from jalview.io.VamsasAppDatastore @@ -75,9 +74,9 @@ public abstract class DatastoreItem { return cdoc.getObject((VorbaId) jv2vobj.get(jvobj)); } - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Returning null VorbaID binding for jalview object " + jvobj); } return null; @@ -96,7 +95,7 @@ public abstract class DatastoreItem if (id == null) { id = cdoc.registerObject(vobj); - Cache.log.debug( + Cache.debug( "Registering new object and returning null for getvObj2jv"); return null; } @@ -123,7 +122,7 @@ public abstract class DatastoreItem if (id == null || vobj.getVorbaId() == null || cdoc.getObject(id) != vobj) { - Cache.log.error("Failed to get id for " + Cache.error("Failed to get id for " + (vobj.isRegisterable() ? "registerable" : "unregisterable") + " object " + vobj); @@ -132,7 +131,7 @@ public abstract class DatastoreItem if (vobj2jv.containsKey(vobj.getVorbaId()) && !(vobj2jv.get(vobj.getVorbaId())).equals(jvobj)) { - Cache.log.debug( + Cache.debug( "Warning? Overwriting existing vamsas id binding for " + vobj.getVorbaId(), new Exception(MessageManager.getString( @@ -141,20 +140,20 @@ public abstract class DatastoreItem else if (jv2vobj.containsKey(jvobj) && !((VorbaId) jv2vobj.get(jvobj)).equals(vobj.getVorbaId())) { - Cache.log.debug( + Cache.debug( "Warning? Overwriting existing jalview object binding for " + jvobj, new Exception(MessageManager.getString( "exception.overwriting_jalview_id_binding"))); } /* - * Cache.log.error("Attempt to make conflicting object binding! "+vobj+" id " + * Cache.error("Attempt to make conflicting object binding! "+vobj+" id " * +vobj.getVorbaId()+" already bound to "+getvObj2jv(vobj)+" and "+jvobj+" * already bound to "+getjv2vObj(jvobj),new Exception("Excessive call to * bindjvvobj")); } */ // we just update the hash's regardless! - Cache.log.debug("Binding " + vobj.getVorbaId() + " to " + jvobj); + Cache.debug("Binding " + vobj.getVorbaId() + " to " + jvobj); vobj2jv.put(vobj.getVorbaId(), jvobj); // JBPNote - better implementing a hybrid invertible hash. jv2vobj.put(jvobj, vobj.getVorbaId()); @@ -172,8 +171,8 @@ public abstract class DatastoreItem { if (this.jvobj != null && this.vobj != null) { - Cache.log.debug("updating dsobj registry. (" - + this.getClass().getName() + ")"); + Cache.debug("updating dsobj registry. (" + this.getClass().getName() + + ")"); } this.jvobj = jvobj; this.vobj = vobj; diff --git a/src/jalview/io/vamsas/DatastoreRegistry.java b/src/jalview/io/vamsas/DatastoreRegistry.java index 37026ba..fe5a917 100644 --- a/src/jalview/io/vamsas/DatastoreRegistry.java +++ b/src/jalview/io/vamsas/DatastoreRegistry.java @@ -24,13 +24,12 @@ import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import jalview.log.JLoggerLog4j; public class DatastoreRegistry implements AutoCloseable { - protected static Logger log = LogManager - .getLogger(DatastoreRegistry.class); + protected static JLoggerLog4j log = JLoggerLog4j + .getLogger(DatastoreRegistry.class.getCanonicalName()); /** * map between Datastore objects and the objects they are handling- used to diff --git a/src/jalview/io/vamsas/Dbref.java b/src/jalview/io/vamsas/Dbref.java index bdef00f..0c8ff09 100644 --- a/src/jalview/io/vamsas/Dbref.java +++ b/src/jalview/io/vamsas/Dbref.java @@ -20,6 +20,7 @@ */ package jalview.io.vamsas; +import jalview.bin.Cache; import jalview.datamodel.DBRefEntry; import jalview.datamodel.SequenceI; import jalview.io.VamsasAppDatastore; @@ -92,7 +93,7 @@ public class Dbref extends Rangetype } else { - jalview.bin.Cache.log.debug( + Cache.debug( "Ignoring mapless DbRef.Map " + jvobj.getSrcAccString()); } @@ -158,8 +159,7 @@ public class Dbref extends Rangetype // TODO: Jalview ignores all the other maps if (vobj.getMapCount() > 1) { - jalview.bin.Cache.log - .debug("Ignoring additional mappings on DbRef: " + Cache.debug("Ignoring additional mappings on DbRef: " + jvobj.getSource() + ":" + jvobj.getAccessionId()); } jalview.datamodel.Mapping mp = new jalview.datamodel.Mapping( @@ -175,8 +175,7 @@ public class Dbref extends Rangetype { DbRef vobj = (DbRef) this.vobj; DBRefEntry jvobj = (DBRefEntry) this.jvobj; - jalview.bin.Cache.log - .debug("Conflict in dbentry update for " + vobj.getAccessionId() + Cache.debug("Conflict in dbentry update for " + vobj.getAccessionId() + vobj.getSource() + " " + vobj.getVorbaId()); // TODO Auto-generated method stub @@ -195,8 +194,7 @@ public class Dbref extends Rangetype // TODO: Jalview ignores all the other maps if (vobj.getMapCount() > 1) { - jalview.bin.Cache.log - .debug("Ignoring additional mappings on DbRef: " + Cache.debug("Ignoring additional mappings on DbRef: " + jvobj.getSource() + ":" + jvobj.getAccessionId()); } jalview.datamodel.Mapping mp = new jalview.datamodel.Mapping( @@ -230,7 +228,7 @@ public class Dbref extends Rangetype } else { - jalview.bin.Cache.log.debug( + Cache.debug( "Ignoring mapless DbRef.Map " + jvobj.getSrcAccString()); } } diff --git a/src/jalview/io/vamsas/Rangetype.java b/src/jalview/io/vamsas/Rangetype.java index 0fed7d7..786a46b 100644 --- a/src/jalview/io/vamsas/Rangetype.java +++ b/src/jalview/io/vamsas/Rangetype.java @@ -20,6 +20,7 @@ */ package jalview.io.vamsas; +import jalview.bin.Cache; import jalview.io.VamsasAppDatastore; import jalview.util.MessageManager; @@ -271,8 +272,7 @@ public abstract class Rangetype extends DatastoreItem { if (!map.getLocal().hasUnit() || map.getMapped().hasUnit()) { - jalview.bin.Cache.log - .warn("using default mapping length of 1:1 for map " + Cache.warn("using default mapping length of 1:1 for map " + (map.isRegistered() ? map.getVorbaId().toString() : (" " + map.toString()))); } diff --git a/src/jalview/io/vamsas/Sequencefeature.java b/src/jalview/io/vamsas/Sequencefeature.java index f8d86d5..a48f8c8 100644 --- a/src/jalview/io/vamsas/Sequencefeature.java +++ b/src/jalview/io/vamsas/Sequencefeature.java @@ -97,7 +97,7 @@ public class Sequencefeature extends Rangetype DataSetAnnotations dsa = (DataSetAnnotations) vobj; if (dsa.getSeqRefCount() != 1) { - Cache.log.warn("Not binding " + dsa.getVorbaId() + Cache.warn("Not binding " + dsa.getVorbaId() + " to Sequence Feature - has multiple dataset sequence references."); return; } @@ -128,7 +128,7 @@ public class Sequencefeature extends Rangetype if (dsa.getSeqRefCount() != 1) { replaceJvObjMapping(feature, null); - Cache.log.warn( + Cache.warn( "Binding of annotation to jalview feature has changed. Removing binding and recreating."); doSync(); // re-verify bindings. } @@ -139,8 +139,7 @@ public class Sequencefeature extends Rangetype getDSAnnotationFromJalview(dsa, feature); if (oldref != dsa.hashCode()) { - Cache.log - .debug("Updated dataset sequence annotation from feature."); + Cache.debug("Updated dataset sequence annotation from feature."); addProvenance(dsa.getProvenance(), "modified"); } } @@ -156,7 +155,7 @@ public class Sequencefeature extends Rangetype { // conflicting update from document - we cannot map this feature anymore. replaceJvObjMapping(feature, null); - Cache.log.warn("annotation (" + dsa.getVorbaId() + Cache.warn("annotation (" + dsa.getVorbaId() + " bound to jalview feature cannot be mapped. Removing binding, deleting feature, and deleting feature."); // - consider deleting the feature ? dsSeq.deleteFeature(feature); @@ -198,7 +197,7 @@ public class Sequencefeature extends Rangetype vSeg.setInclusive(true); if (dsa.getSegCount() > 1) { - Cache.log.debug( + Cache.debug( "About to destroy complex annotation in vamsas document mapped to sequence feature (" + dsa.getVorbaId() + ")"); } diff --git a/src/jalview/io/vamsas/Sequencemapping.java b/src/jalview/io/vamsas/Sequencemapping.java index 0a582e5..3c2aa4c 100644 --- a/src/jalview/io/vamsas/Sequencemapping.java +++ b/src/jalview/io/vamsas/Sequencemapping.java @@ -20,6 +20,7 @@ */ package jalview.io.vamsas; +import jalview.bin.Cache; import jalview.datamodel.AlignedCodonFrame; import jalview.datamodel.AlignmentI; import jalview.datamodel.DBRefEntry; @@ -99,13 +100,13 @@ public class Sequencemapping extends Rangetype } if (from != null && sequenceMapping.getLoc() != from) { - jalview.bin.Cache.log.warn("Probable IMPLEMENTATION ERROR: " + from + Cache.warn("Probable IMPLEMENTATION ERROR: " + from + " doesn't match the local mapping sequence."); } if (ds != null && sequenceMapping.is__stored_in_document() && sequenceMapping.getV_parent() != ds) { - jalview.bin.Cache.log.warn("Probable IMPLEMENTATION ERROR: " + ds + Cache.warn("Probable IMPLEMENTATION ERROR: " + ds + " doesn't match the parent of the bound sequence mapping object."); } } @@ -153,7 +154,7 @@ public class Sequencemapping extends Rangetype SequenceType to = (SequenceType) getjv2vObj(jvto); if (to == null) { - jalview.bin.Cache.log.warn( + Cache.warn( "FIXME NONFATAL - do a second update: Ignoring Forward Reference to seuqence not yet bound to vamsas seuqence object"); return; } @@ -184,7 +185,7 @@ public class Sequencemapping extends Rangetype if (!dnaToProt) { - jalview.bin.Cache.log.warn( + Cache.warn( "Ignoring Mapping - don't support protein to protein mapping in vamsas document yet."); return; } @@ -224,28 +225,26 @@ public class Sequencemapping extends Rangetype // mapping bindjvvobj(mjvmapping.getMap(), sequenceMapping); - jalview.bin.Cache.log.debug( + Cache.debug( "Successfully created mapping " + sequenceMapping.getVorbaId()); } // private void update(jalview.util.MapList mjvmapping, // SequenceMapping sequenceMapping) { - jalview.bin.Cache.log - .error("Not implemented: Jalview Update Alcodon Mapping:TODO!"); + Cache.error("Not implemented: Jalview Update Alcodon Mapping:TODO!"); } private void update(SequenceMapping sequenceMapping, jalview.datamodel.Mapping mjvmapping) { - jalview.bin.Cache.log - .error("Not implemented: Update DBRef Mapping from Jalview"); + Cache.error("Not implemented: Update DBRef Mapping from Jalview"); } private void update(jalview.datamodel.Mapping mjvmapping, SequenceMapping sequenceMapping) { - jalview.bin.Cache.log.error( + Cache.error( "Not implemented: Jalview Update Sequence DBRef Mapping"); } @@ -282,7 +281,7 @@ public class Sequencemapping extends Rangetype } if (sdloc == null || sdmap == null) { - jalview.bin.Cache.log.info("Ignoring non sequence-sequence mapping"); + Cache.info("Ignoring non sequence-sequence mapping"); return; } mobj = this.getvObj2jv(sdloc); @@ -298,7 +297,7 @@ public class Sequencemapping extends Rangetype if (from == null || to == null) { - jalview.bin.Cache.log.error( + Cache.error( "Probable Vamsas implementation error : unbound dataset sequences involved in a mapping are being parsed!"); return; } @@ -389,16 +388,16 @@ public class Sequencemapping extends Rangetype { if (from.getDBRefs() == null && to.getDBRefs() == null) { - if (jalview.bin.Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - jalview.bin.Cache.log.debug("Not matching conjugate refs for " + Cache.debug("Not matching conjugate refs for " + from.getName() + " and " + to.getName()); } return; } - if (jalview.bin.Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - jalview.bin.Cache.log.debug("Matching conjugate refs for " + Cache.debug("Matching conjugate refs for " + from.getName() + " and " + to.getName()); } List fdb = from.getDBRefs(); @@ -422,7 +421,7 @@ public class Sequencemapping extends Rangetype boolean fmpnnl = (fmp != null); // if (fmpnnl && fmp.getTo()!=null) // { - // jalview.bin.Cache.log.debug("Not overwriting existing To reference in + // Cache.debug("Not overwriting existing To reference in // "+fe); // continue; // } diff --git a/src/jalview/io/vamsas/Tree.java b/src/jalview/io/vamsas/Tree.java index 00e4fbc..7d57650 100644 --- a/src/jalview/io/vamsas/Tree.java +++ b/src/jalview/io/vamsas/Tree.java @@ -128,7 +128,7 @@ public class Tree extends DatastoreItem } } catch (Exception e) { - Cache.log.warn("Problems parsing treefile '" + Cache.warn("Problems parsing treefile '" + tree.getNewick(0).getContent() + "'", e); } } @@ -141,7 +141,7 @@ public class Tree extends DatastoreItem @Override public void conflict() { - Cache.log.info( + Cache.info( "Update (with conflict) from vamsas document to alignment associated tree not implemented yet."); } @@ -186,7 +186,7 @@ public class Tree extends DatastoreItem * idata[0] != null) { inputData = (AlignmentView) idata[0]; } ntree = * getNtree(); title = tree.getNewick(0).getTitle(); if (title == null || * title.length() == 0) { title = tree.getTitle(); // hack!!!! } } catch - * (Exception e) { Cache.log.warn("Problems parsing treefile '" + + * (Exception e) { Cache.warn("Problems parsing treefile '" + * tree.getNewick(0).getContent() + "'", e); } */ log.debug("Update the local tree in jalview from the document."); @@ -214,7 +214,7 @@ public class Tree extends DatastoreItem */ private Provenance makeTreeProvenance(AlignmentI jal, TreePanel tp) { - Cache.log.debug("Making Tree provenance for " + tp.getTitle()); + Cache.debug("Making Tree provenance for " + tp.getTitle()); Provenance prov = new Provenance(); prov.addEntry(new Entry()); prov.getEntry(0).setAction("imported " + tp.getTitle()); @@ -259,7 +259,7 @@ public class Tree extends DatastoreItem vInput.addSeg(visSeg); } } - Cache.log.debug("Finished Tree provenance for " + tp.getTitle()); + Cache.debug("Finished Tree provenance for " + tp.getTitle()); return prov; } @@ -297,7 +297,7 @@ public class Tree extends DatastoreItem } if (alsq.size() < sequences.length) { - Cache.log.warn( + Cache.warn( "Not recovered all alignment sequences for given set of input sequence CIGARS"); } return alsq; @@ -319,7 +319,7 @@ public class Tree extends DatastoreItem if (tp.getTree() == null) { - Cache.log.warn( + Cache.warn( "Not updating SequenceTreeMap for " + tree.getVorbaId()); return; } @@ -532,7 +532,7 @@ public class Tree extends DatastoreItem { if (tp.getEntry(pe).getInputCount() > 1) { - Cache.log.warn( + Cache.warn( "Ignoring additional input spec in provenance entry " + tp.getEntry(pe).toString()); } @@ -589,7 +589,7 @@ public class Tree extends DatastoreItem // bidirection alignments yet. if (to < se[1]) { - Cache.log.warn("Ignoring invalid segment in InputData spec."); + Cache.warn("Ignoring invalid segment in InputData spec."); } else { @@ -612,7 +612,7 @@ public class Tree extends DatastoreItem return new Object[] { new AlignmentView(view), jal }; } } - Cache.log.debug( + Cache.debug( "Returning null for input data recovery from provenance."); return null; } @@ -658,7 +658,7 @@ public class Tree extends DatastoreItem return true; } catch (Exception e) { - Cache.log.debug("Failed to parse newick tree string", e); + Cache.debug("Failed to parse newick tree string", e); } return false; } diff --git a/src/jalview/io/vcf/VCFLoader.java b/src/jalview/io/vcf/VCFLoader.java index dadb532..b96de68 100644 --- a/src/jalview/io/vcf/VCFLoader.java +++ b/src/jalview/io/vcf/VCFLoader.java @@ -314,7 +314,7 @@ public class VCFLoader VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY); if (headerLine == null) { - Cache.log.error("VCF reference header not found"); + Cache.error("VCF reference header not found"); return null; } String ref = headerLine.getValue(); @@ -336,7 +336,7 @@ public class VCFLoader } else { - Cache.log.error("VCF reference not found: " + ref); + Cache.error("VCF reference not found: " + ref); } return seq; @@ -429,7 +429,7 @@ public class VCFLoader { if (reference == null) { - Cache.log.error("No VCF ##reference found, defaulting to " + Cache.error("No VCF ##reference found, defaulting to " + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES); reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified } @@ -775,7 +775,7 @@ public class VCFLoader GeneLociI seqCoords = seq.getGeneLoci(); if (seqCoords == null) { - Cache.log.warn(String.format( + Cache.warn(String.format( "Can't query VCF for %s as chromosome coordinates not known", seq.getName())); return null; @@ -790,7 +790,7 @@ public class VCFLoader // returned with the Ensembl sequence; todo: support aliases? if (!vcfSpecies.equalsIgnoreCase(species)) { - Cache.log.warn("No VCF loaded to " + seq.getName() + Cache.warn("No VCF loaded to " + seq.getName() + " as species not matched"); return null; } @@ -820,7 +820,7 @@ public class VCFLoader vcfAssembly); if (newRange == null) { - Cache.log.error( + Cache.error( String.format("Failed to map %s:%s:%s:%d:%d to %s", species, chromosome, seqRef, range[0], range[1], vcfAssembly)); @@ -920,7 +920,7 @@ public class VCFLoader */ String msg = String.format("Error reading VCF for %s:%d-%d: %s ", map.chromosome, vcfStart, vcfEnd,e.getLocalizedMessage()); - Cache.log.error(msg); + Cache.error(msg); } } @@ -1382,7 +1382,7 @@ public class VCFLoader VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId); if (infoHeader == null) { - Cache.log.error("Field " + infoId + " has no INFO header"); + Cache.error("Field " + infoId + " has no INFO header"); return false; } VCFHeaderLineType infoType = infoHeader.getType(); @@ -1423,7 +1423,7 @@ public class VCFLoader if (!badData.contains(token)) { badData.add(token); - Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s", + Cache.error(String.format("Invalid VCF data at %s:%d %s=%s", variant.getContig(), variant.getStart(), infoId, value)); } } diff --git a/src/jalview/javascript/MouseOverListener.java b/src/jalview/javascript/MouseOverListener.java index 6a4d0f8..16b57a4 100644 --- a/src/jalview/javascript/MouseOverListener.java +++ b/src/jalview/javascript/MouseOverListener.java @@ -44,7 +44,7 @@ public class MouseOverListener extends JSFunctionExec if (seq != last || i != index) { // this should really be a trace message. - // Cache.log.debug("Mouse over " + v.getId() + " bound to " + // Cache.debug("Mouse over " + v.getId() + " bound to " // + seq + " at " + index); last = seq; i = index; diff --git a/src/jalview/javascript/log4j/Appender.java b/src/jalview/javascript/log4j/Appender.java deleted file mode 100644 index 1b2b676..0000000 --- a/src/jalview/javascript/log4j/Appender.java +++ /dev/null @@ -1,9 +0,0 @@ -package jalview.javascript.log4j; - -import jalview.javascript.log4j.spi.LoggingEvent; - -public abstract class Appender -{ - public abstract void append(LoggingEvent loggingEvent); - -} diff --git a/src/jalview/javascript/log4j/ConsoleAppender.java b/src/jalview/javascript/log4j/ConsoleAppender.java deleted file mode 100644 index f1aca45..0000000 --- a/src/jalview/javascript/log4j/ConsoleAppender.java +++ /dev/null @@ -1,41 +0,0 @@ -package jalview.javascript.log4j; - -import jalview.javascript.log4j.spi.LoggingEvent; - -public class ConsoleAppender -{ - - private String name; - - private Layout layout; - - - public ConsoleAppender() - { - } - - public ConsoleAppender(Layout layout, String name) - { - this.layout = layout; - this.name = name; - } - - public void setLayout(Layout layout) - { - this.layout = layout; - } - - public void setName(String name) - { - this.name = name; - } - - public void append(LoggingEvent event) - { - - System.out - .println(event.getLevel() + ": " + event.getRenderedMessage()); - - } - -} diff --git a/src/jalview/javascript/log4j/Layout.java b/src/jalview/javascript/log4j/Layout.java deleted file mode 100644 index 46c05d1..0000000 --- a/src/jalview/javascript/log4j/Layout.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) - * Copyright (C) $$Year-Rel$$ The Jalview Authors - * - * This file is part of Jalview. - * - * Jalview is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation, either version 3 - * of the License, or (at your option) any later version. - * - * Jalview is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty - * of MERCHANTABILITY or FITNESS FOR A PARTICULAR - * PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Jalview. If not, see . - * The Jalview Authors are detailed in the 'AUTHORS' file. - */ -package jalview.javascript.log4j; - -import org.apache.logging.log4j.core.layout.PatternLayout; - -import jalview.javascript.log4j.spi.LoggingEvent; -import jalview.javascript.log4j.spi.OptionHandler; -//import org.apache.log4j.TTCCLayout; - -public abstract class Layout implements OptionHandler -{ - - // Note that the line.separator property can be looked up even by - // applets. - public final static String LINE_SEP = System - .getProperty("line.separator"); - - public final static int LINE_SEP_LEN = LINE_SEP.length(); - - /** - * Implement this method to create your own layout format. - */ - abstract public String format(LoggingEvent event); - - /** - * Returns the content type output by this layout. The base class returns - * "text/plain". - */ - public String getContentType() - { - return "text/plain"; - } - - /** - * Returns the header for the layout format. The base class returns - * null. - */ - public String getHeader() - { - return null; - } - - /** - * Returns the footer for the layout format. The base class returns - * null. - */ - public String getFooter() - { - return null; - } - - /** - * If the layout handles the throwable object contained within - * {@link LoggingEvent}, then the layout should return false. - * Otherwise, if the layout ignores throwable object, then the layout should - * return true. If ignoresThrowable is true, the appender is - * responsible for rendering the throwable. - *

- * The {@link SimpleLayout}, {@link TTCCLayout}, {@link PatternLayout} all - * return true. The {@link org.apache.log4j.xml.XMLLayout} - * returns false. - * - * @since 0.8.4 - */ - abstract public boolean ignoresThrowable(); - -} diff --git a/src/jalview/javascript/log4j/Level.java b/src/jalview/javascript/log4j/Level.java deleted file mode 100644 index 582f2de..0000000 --- a/src/jalview/javascript/log4j/Level.java +++ /dev/null @@ -1,273 +0,0 @@ -package jalview.javascript.log4j; - -import java.util.Locale; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamException; -import java.io.Serializable; - -/** - * Defines the minimum set of levels recognized by the system, that is - * OFF, FATAL, ERROR, WARN, - * INFO, DEBUG and ALL. - * - *

- * The Level class may be subclassed to define a larger level set. - *

- * - * @author Ceki Gülcü - */ -public class Level extends Priority implements Serializable -{ - - private static final String ALL_NAME = "ALL"; - - private static final String TRACE_NAME = "TRACE"; - - private static final String DEBUG_NAME = "DEBUG"; - - private static final String INFO_NAME = "INFO"; - - private static final String WARN_NAME = "WARN"; - - private static final String ERROR_NAME = "ERROR"; - - private static final String FATAL_NAME = "FATAL"; - - private static final String OFF_NAME = "OFF"; - - /** - * TRACE level integer value. - * - * @since 1.2.12 - */ - public static final int TRACE_INT = 5000; - - /** - * The OFF has the highest possible rank and is intended to turn - * off logging. - */ - final static public Level OFF = new Level(OFF_INT, OFF_NAME, 0); - - /** - * The FATAL level designates very severe error events that will - * presumably lead the application to abort. - */ - final static public Level FATAL = new Level(FATAL_INT, FATAL_NAME, 0); - - /** - * The ERROR level designates error events that might still allow - * the application to continue running. - */ - final static public Level ERROR = new Level(ERROR_INT, ERROR_NAME, 3); - - /** - * The WARN level designates potentially harmful situations. - */ - final static public Level WARN = new Level(WARN_INT, WARN_NAME, 4); - - /** - * The INFO level designates informational messages that - * highlight the progress of the application at coarse-grained level. - */ - final static public Level INFO = new Level(INFO_INT, INFO_NAME, 6); - - /** - * The DEBUG Level designates fine-grained informational events - * that are most useful to debug an application. - */ - final static public Level DEBUG = new Level(DEBUG_INT, DEBUG_NAME, 7); - - /** - * The TRACE Level designates finer-grained informational events - * than the DEBUGALL has the lowest possible rank and is intended to turn - * on all logging. - */ - final static public Level ALL = new Level(ALL_INT, ALL_NAME, 7); - - /** - * Serialization version id. - */ - static final long serialVersionUID = 3491141966387921974L; - - /** - * Instantiate a Level object. - */ - protected Level(int level, String levelStr, int syslogEquivalent) - { - super(level, levelStr, syslogEquivalent); - } - - /** - * Convert the string passed as argument to a level. If the conversion fails, - * then this method returns {@link #DEBUG}. - */ - public static Level toLevel(String sArg) - { - return toLevel(sArg, Level.DEBUG); - } - - /** - * Convert an integer passed as argument to a level. If the conversion fails, - * then this method returns {@link #DEBUG}. - */ - public static Level toLevel(int val) - { - return toLevel(val, Level.DEBUG); - } - - /** - * Convert an integer passed as argument to a level. If the conversion fails, - * then this method returns the specified default. - */ - public static Level toLevel(int val, Level defaultLevel) - { - switch (val) - { - case ALL_INT: - return ALL; - case DEBUG_INT: - return Level.DEBUG; - case INFO_INT: - return Level.INFO; - case WARN_INT: - return Level.WARN; - case ERROR_INT: - return Level.ERROR; - case FATAL_INT: - return Level.FATAL; - case OFF_INT: - return OFF; - case TRACE_INT: - return Level.TRACE; - default: - return defaultLevel; - } - } - - /** - * Convert the string passed as argument to a level. If the conversion fails, - * then this method returns the value of defaultLevel. - */ - public static Level toLevel(String sArg, Level defaultLevel) - { - if (sArg == null) - { - return defaultLevel; - } - String s = sArg.toUpperCase(Locale.ROOT); - - if (s.equals(ALL_NAME)) - { - return Level.ALL; - } - if (s.equals(DEBUG_NAME)) - { - return Level.DEBUG; - } - if (s.equals(INFO_NAME)) - { - return Level.INFO; - } - if (s.equals(WARN_NAME)) - { - return Level.WARN; - } - if (s.equals(ERROR_NAME)) - { - return Level.ERROR; - } - if (s.equals(FATAL_NAME)) - { - return Level.FATAL; - } - if (s.equals(OFF_NAME)) - { - return Level.OFF; - } - if (s.equals(TRACE_NAME)) - { - return Level.TRACE; - } - // - // For Turkish i problem, see bug 40937 - // - if (s.equals("\u0130NFO")) - { - return Level.INFO; - } - return defaultLevel; - } - - /** - * Custom deserialization of Level. - * - * @param s - * serialization stream. - * @throws IOException - * if IO exception. - * @throws ClassNotFoundException - * if class not found. - */ - private void readObject(final ObjectInputStream s) - throws IOException, ClassNotFoundException - { - s.defaultReadObject(); - level = s.readInt(); - syslogEquivalent = s.readInt(); - levelStr = s.readUTF(); - if (levelStr == null) - { - levelStr = ""; - } - } - - /** - * Serialize level. - * - * @param s - * serialization stream. - * @throws IOException - * if exception during serialization. - */ - private void writeObject(final ObjectOutputStream s) throws IOException - { - s.defaultWriteObject(); - s.writeInt(level); - s.writeInt(syslogEquivalent); - s.writeUTF(levelStr); - } - - /** - * Resolved deserialized level to one of the stock instances. May be overriden - * in classes derived from Level. - * - * @return resolved object. - * @throws ObjectStreamException - * if exception during resolution. - */ - private Object readResolve() throws ObjectStreamException - { - // - // if the deserizalized object is exactly an instance of Level - // - if (getClass() == Level.class) - { - return toLevel(level); - } - // - // extension of Level can't substitute stock item - // - return this; - } - -} diff --git a/src/jalview/javascript/log4j/Logger.java b/src/jalview/javascript/log4j/Logger.java deleted file mode 100644 index bb7eb34..0000000 --- a/src/jalview/javascript/log4j/Logger.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) - * Copyright (C) $$Year-Rel$$ The Jalview Authors - * - * This file is part of Jalview. - * - * Jalview is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation, either version 3 - * of the License, or (at your option) any later version. - * - * Jalview is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty - * of MERCHANTABILITY or FITNESS FOR A PARTICULAR - * PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Jalview. If not, see . - * The Jalview Authors are detailed in the 'AUTHORS' file. - */ -package jalview.javascript.log4j; - -import jalview.javascript.log4j.spi.LoggingEvent; - -import java.util.Hashtable; -import java.util.Map; - -public class Logger -{ - - private static Map registry; - - private String name; - - private Level level; - - private boolean enabled = true; - - private boolean isEnabled; - - private Appender appender; - - private Logger(String name) - { - this.name = name; - } - - public static Logger getLogger(String name) - { - if (registry == null) - { - registry = new Hashtable<>(); - getLogger("root"); - } - Logger logger = registry.get(name); - if (logger == null) - { - registry.put(name, logger = new Logger(name)); - logger.setLevel(Level.INFO); - } - return logger; - } - - public static Logger getRootLogger() - { - return getLogger("root"); - } - - public void setLevel(Level l) - { - this.level = l; - } - - public void addAppender(Appender appender) - { - this.appender = appender; - } - - public boolean isDebugEnabled() - { - return isEnabled; - } - - public void debug(Object o) - { - debug(o, null); - } - - public void debug(Object o, Throwable e) - { - switch (level.level) - { - case Priority.FATAL_INT: - case Priority.ERROR_INT: - case Priority.WARN_INT: - case Priority.INFO_INT: - case Priority.DEBUG_INT: - log(o, e); - break; - } - } - - public void info(Object o) - { - info(o, null); - } - - public void info(Object o, Throwable e) - { - switch (level.level) - { - case Priority.FATAL_INT: - case Priority.ERROR_INT: - case Priority.WARN_INT: - case Priority.INFO_INT: - log(o, e); - break; - } - - } - - public void warn(Object o) - { - warn(o, null); - } - - public void warn(Object o, Throwable e) - { - switch (level.level) - { - case Priority.FATAL_INT: - case Priority.ERROR_INT: - case Priority.WARN_INT: - log(o, e); - break; - } - - } - - public void error(Object o) - { - error(o, null); - } - - public void error(Object o, Throwable e) - { - switch (level.level) - { - case Priority.FATAL_INT: - case Priority.ERROR_INT: - log(o, e); - break; - } - - } - - private void log(Object s, Throwable e) - { - switch (level.level) - { - case Priority.ERROR_INT: - if (appender == null) - { - System.err.println(s); - return; - } - break; - case Priority.WARN_INT: - if (appender == null) - { - System.err.println(s); - return; - } - break; - case Priority.INFO_INT: - if (appender == null) - { - System.out.println(s); - return; - } - break; - case Priority.DEBUG_INT: - if (appender == null) - { - System.out.println(s); - return; - } - break; - } - e.printStackTrace(); - appender.append(new LoggingEvent(this, s.toString(), level)); - } - -} diff --git a/src/jalview/javascript/log4j/Priority.java b/src/jalview/javascript/log4j/Priority.java deleted file mode 100644 index 2ace1eb..0000000 --- a/src/jalview/javascript/log4j/Priority.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Kitching Simon - -package jalview.javascript.log4j; - -/** - Refrain from using this class directly, use - the {@link Level} class instead. - - @author Ceki Gülcü */ -public class Priority { - - transient int level; - transient String levelStr; - transient int syslogEquivalent; - - public final static int OFF_INT = Integer.MAX_VALUE; - public final static int FATAL_INT = 50000; - public final static int ERROR_INT = 40000; - public final static int WARN_INT = 30000; - public final static int INFO_INT = 20000; - public final static int DEBUG_INT = 10000; - //public final static int FINE_INT = DEBUG_INT; - public final static int ALL_INT = Integer.MIN_VALUE; - - // too twisted for J2S -- Level class initializer initializes Priority, which - // creates a - // new Level before Priority is indicated to be a superclass of Level. - /** - * @deprecated Use {@link Level#FATAL} instead. - */ - @Deprecated - final static public Priority FATAL = null;// new Level(FATAL_INT, "FATAL", 0); - - /** - * @deprecated Use {@link Level#ERROR} instead. - */ - @Deprecated - final static public Priority ERROR = null;// new Level(ERROR_INT, "ERROR", 3); - - /** - * @deprecated Use {@link Level#WARN} instead. - */ - @Deprecated - final static public Priority WARN = null;// new Level(WARN_INT, "WARN", 4); - - /** - * @deprecated Use {@link Level#INFO} instead. - */ - @Deprecated - final static public Priority INFO = null;// new Level(INFO_INT, "INFO", 6); - - /** - * @deprecated Use {@link Level#DEBUG} instead. - */ - @Deprecated - final static public Priority DEBUG = null;// new Level(DEBUG_INT, "DEBUG", 7); - - /** - * Default constructor for deserialization. - */ - protected Priority() { - level = DEBUG_INT; - levelStr = "DEBUG"; - syslogEquivalent = 7; - } - - /** - Instantiate a level object. - */ - protected - Priority(int level, String levelStr, int syslogEquivalent) { - this.level = level; - this.levelStr = levelStr; - this.syslogEquivalent = syslogEquivalent; - } - - /** - Two priorities are equal if their level fields are equal. - @since 1.2 - */ - @Override - public - boolean equals(Object o) { - if(o instanceof Priority) { - Priority r = (Priority) o; - return (this.level == r.level); - } else { - return false; - } - } - - /** - Return the syslog equivalent of this priority as an integer. - */ - public - final - int getSyslogEquivalent() { - return syslogEquivalent; - } - - - - /** - Returns true if this level has a higher or equal - level than the level passed as argument, false - otherwise. - -

You should think twice before overriding the default - implementation of isGreaterOrEqual method. - - */ - public - boolean isGreaterOrEqual(Priority r) { - return level >= r.level; - } - - // /** - // Return all possible priorities as an array of Level objects in - // descending order. - // - // @deprecated This method will be removed with no replacement. - // */ - // public - // static - // Priority[] getAllPossiblePriorities() { - // return new Priority[] {Priority.FATAL, Priority.ERROR, Level.WARN, - // Priority.INFO, Priority.DEBUG}; - // } - - - /** - Returns the string representation of this priority. - */ - @Override - final - public - String toString() { - return levelStr; - } - - /** - Returns the integer representation of this level. - */ - public - final - int toInt() { - return level; - } - - // /** - // * @deprecated Please use the {@link Level#toLevel(String)} method instead. - // */ - // public - // static - // Priority toPriority(String sArg) { - // return Level.toLevel(sArg); - // } - - // /** - // * @deprecated Please use the {@link Level#toLevel(int)} method instead. - // */ - // public - // static - // Priority toPriority(int val) { - // return toPriority(val, Priority.DEBUG); - // } - - // /** - // * @deprecated Please use the {@link Level#toLevel(int, Level)} method - // instead. - // */ - // public - // static - // Priority toPriority(int val, Priority defaultPriority) { - // return Level.toLevel(val, (Level) defaultPriority); - // } - // - // /** - // * @deprecated Please use the {@link Level#toLevel(String, Level)} method - // instead. - // */ - // public - // static - // Priority toPriority(String sArg, Priority defaultPriority) { - // return Level.toLevel(sArg, (Level) defaultPriority); - // } -} diff --git a/src/jalview/javascript/log4j/SimpleLayout.java b/src/jalview/javascript/log4j/SimpleLayout.java deleted file mode 100644 index 9e5cbba..0000000 --- a/src/jalview/javascript/log4j/SimpleLayout.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) - * Copyright (C) $$Year-Rel$$ The Jalview Authors - * - * This file is part of Jalview. - * - * Jalview is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation, either version 3 - * of the License, or (at your option) any later version. - * - * Jalview is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty - * of MERCHANTABILITY or FITNESS FOR A PARTICULAR - * PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Jalview. If not, see . - * The Jalview Authors are detailed in the 'AUTHORS' file. - */ -package jalview.javascript.log4j; - -import jalview.javascript.log4j.spi.LoggingEvent; - -public class SimpleLayout extends Layout -{ - - StringBuffer sbuf = new StringBuffer(128); - - @Override - public void activateOptions() - { - // TODO Auto-generated method stub - - } - - @Override - public String format(LoggingEvent event) - { - - sbuf.setLength(0); - sbuf.append(event.getLevel().toString()); - sbuf.append(" - "); - sbuf.append(event.getRenderedMessage()); - sbuf.append(LINE_SEP); - return sbuf.toString(); - } - @Override - public boolean ignoresThrowable() - { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/src/jalview/javascript/log4j/WriterAppender.java b/src/jalview/javascript/log4j/WriterAppender.java deleted file mode 100644 index 1a015f2..0000000 --- a/src/jalview/javascript/log4j/WriterAppender.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package jalview.javascript.log4j; - -public abstract class WriterAppender extends Appender -{ - -} diff --git a/src/jalview/javascript/log4j/spi/LoggingEvent.java b/src/jalview/javascript/log4j/spi/LoggingEvent.java deleted file mode 100644 index 669ae52..0000000 --- a/src/jalview/javascript/log4j/spi/LoggingEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) - * Copyright (C) $$Year-Rel$$ The Jalview Authors - * - * This file is part of Jalview. - * - * Jalview is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation, either version 3 - * of the License, or (at your option) any later version. - * - * Jalview is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty - * of MERCHANTABILITY or FITNESS FOR A PARTICULAR - * PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Jalview. If not, see . - * The Jalview Authors are detailed in the 'AUTHORS' file. - */ -package jalview.javascript.log4j.spi; - -import jalview.javascript.log4j.Logger; - -public class LoggingEvent -{ - - private Object level; - - private String msg; - - private Logger logger; - - public LoggingEvent(Logger logger, String level, Object message) - { - this.logger = logger; - this.level = level; - this.msg = message.toString(); - - } - - public Object getLevel() - { - return level; - } - - public String getRenderedMessage() - { - return msg; - } -} diff --git a/src/jalview/javascript/log4j/spi/OptionHandler.java b/src/jalview/javascript/log4j/spi/OptionHandler.java deleted file mode 100644 index 9cd0f01..0000000 --- a/src/jalview/javascript/log4j/spi/OptionHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package jalview.javascript.log4j.spi; - -public interface OptionHandler -{ - - void activateOptions(); - -} diff --git a/src/jalview/jbgui/GAlignFrame.java b/src/jalview/jbgui/GAlignFrame.java index 6685c67..6aaba84 100755 --- a/src/jalview/jbgui/GAlignFrame.java +++ b/src/jalview/jbgui/GAlignFrame.java @@ -1063,7 +1063,7 @@ public class GAlignFrame extends JInternalFrame }); seqLimits.setText( MessageManager.getString("label.show_sequence_limits")); - seqLimits.setState(jalview.bin.Cache.getDefault("SHOW_JVSUFFIX", true)); + seqLimits.setState(Cache.getDefault("SHOW_JVSUFFIX", true)); seqLimits.addActionListener(new ActionListener() { @Override @@ -1214,7 +1214,7 @@ public class GAlignFrame extends JInternalFrame padGapsMenuitem.setText(MessageManager.getString("label.pad_gaps")); padGapsMenuitem - .setState(jalview.bin.Cache.getDefault("PAD_GAPS", false)); + .setState(Cache.getDefault("PAD_GAPS", false)); padGapsMenuitem.addActionListener(new ActionListener() { @Override @@ -1358,7 +1358,7 @@ public class GAlignFrame extends JInternalFrame autoCalculate.setText( MessageManager.getString("label.autocalculate_consensus")); autoCalculate.setState( - jalview.bin.Cache.getDefault("AUTO_CALC_CONSENSUS", true)); + Cache.getDefault("AUTO_CALC_CONSENSUS", true)); autoCalculate.addActionListener(new ActionListener() { @Override @@ -1372,7 +1372,7 @@ public class GAlignFrame extends JInternalFrame sortByTree.setToolTipText("" + MessageManager.getString( "label.enable_automatically_sort_alignment_when_open_new_tree")); sortByTree - .setState(jalview.bin.Cache.getDefault("SORT_BY_TREE", false)); + .setState(Cache.getDefault("SORT_BY_TREE", false)); sortByTree.addActionListener(new ActionListener() { @Override diff --git a/src/jalview/jbgui/GPreferences.java b/src/jalview/jbgui/GPreferences.java index 37ba654..f7d9860 100755 --- a/src/jalview/jbgui/GPreferences.java +++ b/src/jalview/jbgui/GPreferences.java @@ -2793,7 +2793,7 @@ public class GPreferences extends JPanel } else { - Cache.log.error( + Cache.error( "Preset '" + value + "' [key:" + key + "] not implemented"); } @@ -2813,7 +2813,7 @@ public class GPreferences extends JPanel .getSelectedItem(); } catch (Exception ex) { - Cache.log.error( + Cache.error( "Problem casting Combo entry to IntKeyStringValueEntry."); e = null; } @@ -2831,7 +2831,7 @@ public class GPreferences extends JPanel e = (IntKeyStringValueEntry) backupfilesPresetsCombo2.getItemAt(i); } catch (Exception ex) { - Cache.log.error( + Cache.error( "Problem casting Combo entry to IntKeyStringValueEntry. Skipping item. "); continue; } @@ -3279,7 +3279,7 @@ public class GPreferences extends JPanel i = ((Integer) s.getValue()).intValue(); } catch (Exception e) { - Cache.log.error( + Cache.error( "Exception casting the initial value of s.getValue()"); } } @@ -3315,7 +3315,7 @@ public class GPreferences extends JPanel i = (Integer) s.getValue(); } catch (Exception e) { - Cache.log.error("Failed casting (Integer) JSpinner s.getValue()"); + Cache.error("Failed casting (Integer) JSpinner s.getValue()"); } return i; } diff --git a/src/jalview/jbgui/GWsPreferences.java b/src/jalview/jbgui/GWsPreferences.java index 84de493..928b370 100644 --- a/src/jalview/jbgui/GWsPreferences.java +++ b/src/jalview/jbgui/GWsPreferences.java @@ -20,6 +20,7 @@ */ package jalview.jbgui; +import jalview.bin.Cache; import jalview.util.MessageManager; import java.awt.BorderLayout; @@ -432,7 +433,7 @@ public class GWsPreferences extends JPanel wsMenuRefreshButs.add(resetWs, null); wsMenuRefreshButs.add(progressBar, null); myBorderlayout.setHgap(3); - if (jalview.bin.Cache.getDefault("ENABLE_RSBS_EDITOR", false)) + if (Cache.getDefault("ENABLE_RSBS_EDITOR", false)) { JTabbedPane listPanels = new JTabbedPane(); listPanels.addTab("JABAWS Servers", wsListPanel); diff --git a/src/jalview/log/JLogger.java b/src/jalview/log/JLogger.java new file mode 100644 index 0000000..03b664a --- /dev/null +++ b/src/jalview/log/JLogger.java @@ -0,0 +1,181 @@ +package jalview.log; + +import java.util.HashMap; +import java.util.Map; + +import jalview.bin.Cache; +import jalview.util.Platform; + +public abstract class JLogger implements JLoggerI +{ + protected String name; + + protected LogLevel level; + + private Object logger = null; + + private static Map registry = new HashMap<>(); + + // implement these abstract methods + protected abstract void loggerSetup(); + + public abstract boolean loggerExists(); + + protected abstract void loggerSetLevel(LogLevel level); + + protected abstract void loggerLogMessage(LogLevel level, String message, + Throwable t); + + public static LogLevel toLevel(String levelString) + { + try + { + return LogLevel.valueOf(levelString); + } catch (IllegalArgumentException e) + { + Cache.error("Could not parse LogLevel '" + levelString + "'", e); + return LogLevel.INFO; + } + } + + public static JLogger getLogger(String name) + { + return getLogger(name, LogLevel.INFO); + } + + public static JLogger getLogger(String name, LogLevel loglevel) + { + return registry.containsKey(name) ? (JLogger) registry.get(name) : null; + } + + protected JLogger() + { + } + + protected JLogger(String name, LogLevel level) + { + this.name = name; + this.level = level; + this.loggerSetup(); + this.registryStore(); + } + + protected void registryStore() + { + registry.put(this.name, this); + } + + protected static boolean registryContainsKey(String name) + { + return registry.containsKey(name); + } + + protected static JLogger registryGet(String name) + { + return registry.get(name); + } + + public LogLevel getLevel() + { + return this.level; + } + + public void setLevel(LogLevel level) + { + this.level = level; + if (loggerExists()) + loggerSetLevel(level); + } + + private boolean println(LogLevel level, String message, Throwable t) + { + if (!loggerExists() || Platform.isJS()) + { + String logLine = String.format("%s: %s", level.toString(), message); + System.out.println(logLine); + if (t != null) + { + if (level.compareTo(LogLevel.DEBUG) <= 0) + t.printStackTrace(System.err); + else + System.err.println(t.getMessage()); + } + return false; + } + else + { + loggerLogMessage(level, message, t); + return true; + } + } + + public void trace(String message) + { + trace(message, null); + } + + public void trace(String message, Throwable t) + { + println(LogLevel.TRACE, message, t); + } + + public void debug(String message) + { + debug(message, null); + } + + public void debug(String message, Throwable t) + { + println(LogLevel.DEBUG, message, t); + } + + public void info(String message) + { + info(message, null); + } + + public void info(String message, Throwable t) + { + println(LogLevel.INFO, message, t); + } + + public void warn(String message) + { + warn(message, null); + } + + public void warn(String message, Throwable t) + { + println(LogLevel.WARN, message, t); + } + + public void error(String message) + { + error(message, null); + } + + public void error(String message, Throwable t) + { + println(LogLevel.ERROR, message, t); + } + + public void fatal(String message) + { + fatal(message, null); + } + + public void fatal(String message, Throwable t) + { + println(LogLevel.FATAL, message, t); + } + + public boolean isDebugEnabled() + { + return level.compareTo(LogLevel.DEBUG) <= 0; + } + + public boolean isTraceEnabled() + { + return level.compareTo(LogLevel.TRACE) <= 0; + } +} diff --git a/src/jalview/log/JLoggerI.java b/src/jalview/log/JLoggerI.java new file mode 100644 index 0000000..94f149b --- /dev/null +++ b/src/jalview/log/JLoggerI.java @@ -0,0 +1,41 @@ +package jalview.log; + +public interface JLoggerI +{ + public enum LogLevel + { + ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL + } + + public LogLevel getLevel(); + + public void setLevel(LogLevel level); + + public void trace(String message); + + public void trace(String message, Throwable t); + + public void debug(String message); + + public void debug(String message, Throwable t); + + public void info(String message); + + public void info(String message, Throwable t); + + public void warn(String message); + + public void warn(String message, Throwable t); + + public void error(String message); + + public void error(String message, Throwable t); + + public void fatal(String message); + + public void fatal(String message, Throwable t); + + public boolean isDebugEnabled(); + + public boolean isTraceEnabled(); +} diff --git a/src/jalview/log/JLoggerLog4j.java b/src/jalview/log/JLoggerLog4j.java new file mode 100644 index 0000000..ca24e30 --- /dev/null +++ b/src/jalview/log/JLoggerLog4j.java @@ -0,0 +1,137 @@ +package jalview.log; + +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.Appender; + +import jalview.util.Log4j; +import jalview.util.Platform; + +public class JLoggerLog4j extends JLogger implements JLoggerI +{ + private Logger logger = null; + + public static JLoggerLog4j getLogger(String name) + { + return getLogger(name, LogLevel.INFO); + } + + public static JLoggerLog4j getLogger(String name, LogLevel loglevel) + { + return registryContainsKey(name) ? (JLoggerLog4j) registryGet(name) + : new JLoggerLog4j(name, loglevel); + } + + private JLoggerLog4j(String name, LogLevel level) + { + // super(name, level); + this.name = name; + this.level = level; + this.loggerSetup(); + this.registryStore(); + } + + @Override + protected void loggerSetup() + { + if (!Platform.isJS()) + this.logger = Log4j.isInit() ? Log4j.getLogger(this.name, this.level) + : null; + } + + @Override + public boolean loggerExists() + { + return logger != null; + } + + @Override + protected void loggerSetLevel(JLoggerI.LogLevel level) + { + if (loggerExists()) + { + Log4j.setLevel(logger, level); + } + } + + @Override + protected void loggerLogMessage(LogLevel level, String message, + Throwable t) + { + if (!loggerExists()) + return; + if (t != null) + { + switch (level) + { + case FATAL: + logger.fatal(message, t); + break; + case ERROR: + logger.error(message, t); + break; + case WARN: + logger.warn(message, t); + break; + case INFO: + logger.info(message, t); + break; + case DEBUG: + logger.debug(message, t); + break; + case TRACE: + logger.trace(message, t); + break; + case ALL: + logger.trace(message, t); + break; + } + } + else + { + switch (level) + { + case FATAL: + logger.fatal(message); + break; + case ERROR: + logger.error(message); + break; + case WARN: + logger.warn(message); + break; + case INFO: + logger.info(message); + break; + case DEBUG: + logger.debug(message); + break; + case TRACE: + logger.trace(message); + break; + case ALL: + logger.trace(message); + break; + } + } + } + + private Logger getLoggerObject() + { + return this.logger; + } + + public synchronized static void addAppender(JLoggerLog4j l1, + Appender appender) + { + if (!Platform.isJS()) + Log4j.addAppender(l1.getLoggerObject(), appender); + } + + public synchronized static void addAppender(JLoggerLog4j l1, + JLoggerLog4j l2, String name) + { + if (!Platform.isJS()) + Log4j.addAppender(l1.getLoggerObject(), l2.getLoggerObject(), name); + } + +} diff --git a/src/jalview/gui/JalviewAppender.java b/src/jalview/log/JalviewAppender.java similarity index 72% rename from src/jalview/gui/JalviewAppender.java rename to src/jalview/log/JalviewAppender.java index 229a1f6..07239f8 100644 --- a/src/jalview/gui/JalviewAppender.java +++ b/src/jalview/log/JalviewAppender.java @@ -18,7 +18,7 @@ * along with Jalview. If not, see . * The Jalview Authors are detailed in the 'AUTHORS' file. */ -package jalview.gui; +package jalview.log; import java.io.Serializable; import java.nio.charset.StandardCharsets; @@ -26,11 +26,15 @@ import java.nio.charset.StandardCharsets; import javax.swing.JTextArea; import javax.swing.SwingUtilities; +import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; -import org.apache.logging.log4j.core.layout.PatternLayout; +import org.apache.logging.log4j.core.config.Property; + +import jalview.log.JLoggerI.LogLevel; +import jalview.util.Log4j; /** * From http://textareaappender.zcage.com/ the means to capture the logs, too. @@ -38,26 +42,26 @@ import org.apache.logging.log4j.core.layout.PatternLayout; */ public class JalviewAppender extends AbstractAppender { + public final static String NAME = "JalviewAppender"; - private final static Layout simpleLayout; - - static + public JalviewAppender() { - // SimpleLayout pattern found from - // https://logging.apache.org/log4j/log4j-2.12.4/manual/migration.html - simpleLayout = PatternLayout.newBuilder().withPattern("%level - %m%n") - .build(); + this(LogLevel.INFO); } - protected JalviewAppender() + public JalviewAppender(LogLevel loglevel) { - this("JalviewAppender", null, simpleLayout); + super(NAME, + Log4j.getThresholdFilter(loglevel == null ? Level.INFO + : Log4j.log4jLevel(loglevel)), + Log4j.getSimpleLayout(), false, new Property[0]); } protected JalviewAppender(String name, Filter filter, - Layout layout) + Layout layout, boolean ignoreExceptions, + Property[] properties) { - super(name, filter, layout); + super(name, filter, layout, ignoreExceptions, properties); // TODO Auto-generated constructor stub } @@ -74,8 +78,8 @@ public class JalviewAppender extends AbstractAppender */ public void append(LogEvent logEvent) { - final String message = new String(simpleLayout.toByteArray(logEvent), - StandardCharsets.UTF_8); + final String message = new String( + this.getLayout().toByteArray(logEvent), StandardCharsets.UTF_8); // Append formatted message to textarea using the Swing Thread. SwingUtilities.invokeLater(new Runnable() diff --git a/src/jalview/project/Jalview2XML.java b/src/jalview/project/Jalview2XML.java index acfeb2a..e132bef 100644 --- a/src/jalview/project/Jalview2XML.java +++ b/src/jalview/project/Jalview2XML.java @@ -576,7 +576,7 @@ public class Jalview2XML } catch (Exception e) { - Cache.log.error("Couln't write Jalview state to " + statefile, e); + Cache.error("Couln't write Jalview state to " + statefile, e); // TODO: inform user of the problem - they need to know if their data was // not saved ! if (errorMessage == null) @@ -882,7 +882,7 @@ public class Jalview2XML System.err.println("error writing date: " + e.toString()); } object.setVersion( - jalview.bin.Cache.getDefault("VERSION", "Development Build")); + Cache.getDefault("VERSION", "Development Build")); /** * rjal is full height alignment, jal is actual alignment with full metadata @@ -1109,7 +1109,7 @@ public class Jalview2XML } else { - Cache.log.error( + Cache.error( "Failed to save viewer state for " + viewerType); } } @@ -1632,7 +1632,7 @@ public class Jalview2XML .getHiddenColumns(); if (hidden == null) { - warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this."); + Cache.warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this."); } else { @@ -1801,7 +1801,7 @@ public class Jalview2XML object.getPcaViewer().add(viewer); } catch (Throwable t) { - Cache.log.error("Error saving PCA: " + t.getMessage()); + Cache.error("Error saving PCA: " + t.getMessage()); } } @@ -2091,7 +2091,7 @@ public class Jalview2XML } else if (!matchedFile.equals(pdbentry.getFile())) { - Cache.log.warn( + Cache.warn( "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): " + pdbentry.getFile()); } @@ -2389,7 +2389,7 @@ public class Jalview2XML calcIdParam.getParameters().replace("|\\n|", "\n")); } catch (IOException x) { - warn("Couldn't parse parameter data for " + Cache.warn("Couldn't parse parameter data for " + calcIdParam.getCalcId(), x); return false; } @@ -2417,7 +2417,7 @@ public class Jalview2XML } else { - warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server."); + Cache.warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server."); return false; } } @@ -2461,7 +2461,7 @@ public class Jalview2XML return id.toString(); } // give up and warn that something has gone wrong - warn("Cannot find ID for object in external mapping : " + jvobj); + Cache.warn("Cannot find ID for object in external mapping : " + jvobj); } return altCode; } @@ -2598,12 +2598,12 @@ public class Jalview2XML mp.setDseqFor(jmpid); if (!seqRefIds.containsKey(jmpid)) { - jalview.bin.Cache.log.debug("creatign new DseqFor ID"); + Cache.debug("creatign new DseqFor ID"); seqRefIds.put(jmpid, ps); } else { - jalview.bin.Cache.log.debug("reusing DseqFor ID"); + Cache.debug("reusing DseqFor ID"); } // mp.setMappingChoice(mpc); @@ -3229,7 +3229,7 @@ public class Jalview2XML } else { - warn("Couldn't find entry in Jalview Jar for " + jarEntryName); + Cache.warn("Couldn't find entry in Jalview Jar for " + jarEntryName); } } catch (Exception ex) { @@ -4204,7 +4204,7 @@ public class Jalview2XML tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews()); if (tp == null) { - warn("There was a problem recovering stored Newick tree: \n" + Cache.warn("There was a problem recovering stored Newick tree: \n" + tree.getNewick()); continue; } @@ -4366,7 +4366,7 @@ public class Jalview2XML else { errorMessage = ("The Jmol views in this project were imported\nfrom an older version of Jalview.\nPlease review the sequence colour associations\nin the Colour by section of the Jmol View menu.\n\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747"); - warn(errorMessage); + Cache.warn(errorMessage); } } } @@ -4421,7 +4421,7 @@ public class Jalview2XML } catch (IllegalArgumentException | NullPointerException e) { // TODO JAL-3619 show error dialog / offer an alternative viewer - Cache.log.error("Invalid structure viewer type: " + type); + Cache.error("Invalid structure viewer type: " + type); } } @@ -4953,7 +4953,7 @@ public class Jalview2XML } else { - warn("Couldn't recover parameters for " + Cache.warn("Couldn't recover parameters for " + calcIdParam.getCalcId()); } } @@ -5229,10 +5229,7 @@ public class Jalview2XML String id = object.getViewport().get(0).getSequenceSetId(); if (skipList.containsKey(id)) { - if (Cache.log != null && Cache.log.isDebugEnabled()) - { - Cache.log.debug("Skipping seuqence set id " + id); - } + Cache.debug("Skipping seuqence set id " + id); return true; } return false; @@ -5284,14 +5281,14 @@ public class Jalview2XML { if (ds != null && ds != seqSetDS) { - warn("JAL-3171 regression: Overwriting a dataset reference for an alignment" + Cache.warn("JAL-3171 regression: Overwriting a dataset reference for an alignment" + " - CDS/Protein crossreference data may be lost"); if (xtant_ds != null) { // This can only happen if the unique sequence set ID was bound to a // dataset that did not contain any of the sequences in the view // currently being restored. - warn("JAL-3171 SERIOUS! TOTAL CONFUSION - please consider contacting the Jalview Development team so they can investigate why your project caused this message to be displayed."); + Cache.warn("JAL-3171 SERIOUS! TOTAL CONFUSION - please consider contacting the Jalview Development team so they can investigate why your project caused this message to be displayed."); } } ds = seqSetDS; @@ -5316,7 +5313,7 @@ public class Jalview2XML SequenceI[] dsseqs = new SequenceI[dseqs.size()]; dseqs.copyInto(dsseqs); ds = new jalview.datamodel.Alignment(dsseqs); - debug("Created new dataset " + vamsasSet.getDatasetId() + Cache.debug("Created new dataset " + vamsasSet.getDatasetId() + " for alignment " + System.identityHashCode(al)); addDatasetRef(vamsasSet.getDatasetId(), ds); } @@ -5369,7 +5366,7 @@ public class Jalview2XML AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds); if (prevDS != null && prevDS != ds) { - warn("Dataset sequence appears in many datasets: " + Cache.warn("Dataset sequence appears in many datasets: " + restoredSeq.getDsseqid()); // TODO: try to merge! } @@ -5575,7 +5572,7 @@ public class Jalview2XML { if (dataset.getDataset() != null) { - warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment..."); + Cache.warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment..."); } String datasetId = makeHashCode(dataset, null); if (datasetId == null) @@ -5711,7 +5708,7 @@ public class Jalview2XML seqRefIds.put(sqid, djs); } - jalview.bin.Cache.log.debug("about to recurse on addDBRefs."); + Cache.debug("about to recurse on addDBRefs."); addDBRefs(djs, ms); } @@ -5764,62 +5761,6 @@ public class Jalview2XML private Hashtable jvids2vobj; - private void warn(String msg) - { - warn(msg, null); - } - - private void warn(String msg, Exception e) - { - if (Cache.log != null) - { - if (e != null) - { - Cache.log.warn(msg, e); - } - else - { - Cache.log.warn(msg); - } - } - else - { - System.err.println("Warning: " + msg); - if (e != null) - { - e.printStackTrace(); - } - } - } - - private void debug(String string) - { - debug(string, null); - } - - private void debug(String msg, Exception e) - { - if (Cache.log != null) - { - if (e != null) - { - Cache.log.debug(msg, e); - } - else - { - Cache.log.debug(msg); - } - } - else - { - System.err.println("Warning: " + msg); - if (e != null) - { - e.printStackTrace(); - } - } - } - /** * set the object to ID mapping tables used to write/recover objects and XML * ID strings for the jalview project. If external tables are provided then @@ -5878,7 +5819,7 @@ public class Jalview2XML if (!jvann.annotationId.equals(anid)) { // TODO verify that this is the correct behaviour - this.warn("Overriding Annotation ID for " + anid + Cache.warn("Overriding Annotation ID for " + anid + " from different id : " + jvann.annotationId); jvann.annotationId = anid; } @@ -5893,7 +5834,7 @@ public class Jalview2XML } else { - Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id); + Cache.debug("Ignoring " + jvobj.getClass() + " (ID = " + id); } } } @@ -5963,7 +5904,7 @@ public class Jalview2XML } else { - warn("Couldn't find entry in Jalview Jar for " + jarEntryName); + Cache.warn("Couldn't find entry in Jalview Jar for " + jarEntryName); } } catch (Exception ex) { @@ -6113,7 +6054,7 @@ public class Jalview2XML } } catch (Exception ex) { - Cache.log.error("Error loading PCA: " + ex.toString()); + Cache.error("Error loading PCA: " + ex.toString()); } } @@ -6173,7 +6114,7 @@ public class Jalview2XML }); } catch (InvocationTargetException | InterruptedException ex) { - warn("Unexpected error when opening " + viewerType + Cache.warn("Unexpected error when opening " + viewerType + " structure viewer", ex); } } @@ -6280,7 +6221,7 @@ public class Jalview2XML } } catch (IOException e) { - Cache.log.error("Error restoring Jmol session: " + e.toString()); + Cache.error("Error restoring Jmol session: " + e.toString()); } return null; } @@ -6533,7 +6474,7 @@ public class Jalview2XML maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16)); } catch (Exception e) { - Cache.log.warn("Couldn't parse out graduated feature color.", e); + Cache.warn("Couldn't parse out graduated feature color.", e); } NoValueColour noCol = colourModel.getNoValueColour(); diff --git a/src/jalview/structure/StructureSelectionManager.java b/src/jalview/structure/StructureSelectionManager.java index b4bd781..e4dc137 100644 --- a/src/jalview/structure/StructureSelectionManager.java +++ b/src/jalview/structure/StructureSelectionManager.java @@ -441,8 +441,8 @@ public class StructureSelectionManager } catch (SiftsException e) { isMapUsingSIFTs = false; - Cache.log.error("SIFTS mapping failed", e); - Cache.log.error("Falling back on Needleman & Wunsch alignment"); + Cache.error("SIFTS mapping failed", e); + Cache.error("Falling back on Needleman & Wunsch alignment"); siftsClient = null; } @@ -556,7 +556,7 @@ public class StructureSelectionManager } catch (SiftsException e) { // fall back to NW alignment - Cache.log.error(e.getMessage()); + Cache.error(e.getMessage()); StructureMapping nwMapping = getNWMappings(seq, pdbFile, targetChainId, maxChain, pdb, maxAlignseq); seqToStrucMapping.add(nwMapping); diff --git a/src/jalview/structures/models/AAStructureBindingModel.java b/src/jalview/structures/models/AAStructureBindingModel.java index f1f2d30..a1b616c 100644 --- a/src/jalview/structures/models/AAStructureBindingModel.java +++ b/src/jalview/structures/models/AAStructureBindingModel.java @@ -1497,7 +1497,7 @@ public abstract class AAStructureBindingModel saveSession(f); } catch (IOException e) { - Cache.log.error(String.format("Error saving %s session: %s", prefix, + Cache.error(String.format("Error saving %s session: %s", prefix, e.toString())); } diff --git a/src/jalview/urls/UrlLinkTableModel.java b/src/jalview/urls/UrlLinkTableModel.java index a0f42f0..ad63051 100644 --- a/src/jalview/urls/UrlLinkTableModel.java +++ b/src/jalview/urls/UrlLinkTableModel.java @@ -101,7 +101,7 @@ public class UrlLinkTableModel extends AbstractTableModel dataProvider.setUrlData(data); } catch (IllegalArgumentException ex) { - Cache.log.error(ex.getMessage()); + Cache.error(ex.getMessage()); } } }); diff --git a/src/jalview/util/BrowserLauncher.java b/src/jalview/util/BrowserLauncher.java index 8119daa..dbd9177 100755 --- a/src/jalview/util/BrowserLauncher.java +++ b/src/jalview/util/BrowserLauncher.java @@ -20,6 +20,8 @@ */ package jalview.util; +import jalview.bin.Cache; + import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; @@ -712,7 +714,7 @@ public class BrowserLauncher case OTHER: default: - browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox"); + browser = Cache.getDefault("DEFAULT_BROWSER", "firefox"); break; } diff --git a/src/jalview/util/Log4j.java b/src/jalview/util/Log4j.java index e6c660b..05c641b 100644 --- a/src/jalview/util/Log4j.java +++ b/src/jalview/util/Log4j.java @@ -6,18 +6,151 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.appender.ConsoleAppender; import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.LoggerConfig; +import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; +import org.apache.logging.log4j.core.config.builder.api.FilterComponentBuilder; +import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder; +import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; +import org.apache.logging.log4j.core.filter.ThresholdFilter; +import org.apache.logging.log4j.core.layout.PatternLayout; + +import jalview.log.JLogger; +import jalview.log.JalviewAppender; public class Log4j { + + public final static String SIMPLE_PATTERN = "%level - %m%n"; + + private static boolean init = false; + + public static boolean isInit() + { + return init; + } + + public static Level log4jLevel(JLogger.LogLevel loglevel) + { + return Level.toLevel(loglevel.toString()); + } + + public static void init(JLogger.LogLevel myLevel) + { + init(log4jLevel(myLevel)); + } + + public static void init(Level myLevel) + { + if (init) + return; + try + { + // configure the root logger to stderr + ConfigurationBuilder configBuilder = Log4j + .getConfigurationBuilder(); + + configBuilder.setStatusLevel(Level.WARN); + + String consoleLoggerName = "STDERR"; + AppenderComponentBuilder appenderBuilder = configBuilder + .newAppender(consoleLoggerName, "Console"); + appenderBuilder.addAttribute("target", + ConsoleAppender.Target.SYSTEM_ERR); + appenderBuilder.add(Log4j.getSimpleLayoutBuilder()); + appenderBuilder.add(Log4j.getThresholdFilterBuilder()); + configBuilder.add(appenderBuilder); + + configBuilder.add(configBuilder.newRootLogger(myLevel) + .add(configBuilder.newAppenderRef(consoleLoggerName))); + + Configurator.initialize(configBuilder.build()); + + init = true; + } catch (Exception e) + { + System.err.println("Problems initializing the log4j system\n"); + e.printStackTrace(System.err); + } + } + + public static Logger getLogger(String name) + { + return getLogger(name, Level.INFO); + } + + public static Logger getLogger(String name, JLogger.LogLevel loglevel) + { + return getLogger(name, log4jLevel(loglevel)); + } + + public static Logger getLogger(String name, Level level) + { + Logger logger = LogManager.getLogger(name); + Log4j.setLevel(logger, level); + return logger; + } + + public static ConfigurationBuilder getConfigurationBuilder() + { + return ConfigurationFactory.newConfigurationBuilder(); + } + + public static Layout getSimpleLayout() + { + return PatternLayout.newBuilder().withPattern(SIMPLE_PATTERN).build(); + } + + public static LayoutComponentBuilder getSimpleLayoutBuilder() + { + return getConfigurationBuilder().newLayout("PatternLayout") + .addAttribute("pattern", Log4j.SIMPLE_PATTERN); + } + + public static Filter getThresholdFilter(Level level) + { + return ThresholdFilter.createFilter(level, Filter.Result.ACCEPT, + Filter.Result.NEUTRAL); + } + + public static FilterComponentBuilder getThresholdFilterBuilder() + { + return getConfigurationBuilder().newFilter("ThresholdFilter", + Filter.Result.ACCEPT, Filter.Result.NEUTRAL); + } + + public static void setLevel(Logger logger, JLogger.LogLevel loglevel) + { + setLevel(logger, log4jLevel(loglevel)); + } + public static void setLevel(Logger logger, Level level) { - LoggerContext context = (LoggerContext) LogManager.getContext(false); - Configuration config = context.getConfiguration(); - LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); - loggerConfig.setLevel(level); + if (!Platform.isJS()) + { + LoggerContext context = (LoggerContext) LogManager.getContext(false); + Configuration config = context.getConfiguration(); + LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); + loggerConfig.setLevel(level); + + Map appenders = config.getAppenders(); + + Appender jappender = config.getAppender(JalviewAppender.NAME); + + context.updateLoggers(); + } + } + + public static void setRootLevel(JLogger.LogLevel loglevel) + { + setRootLevel(log4jLevel(loglevel)); } public static void setRootLevel(Level level) @@ -25,6 +158,14 @@ public class Log4j setLevel(LogManager.getRootLogger(), level); } + public static Appender getAppender(String name) + { + LoggerContext context = (LoggerContext) LogManager.getContext(false); + Configuration config = context.getConfiguration(); + Map appenders = config.getAppenders(); + return appenders.get(name); + } + public static void addAppender(Logger logger, Logger logger2, String name2) { @@ -35,14 +176,25 @@ public class Log4j .getAppenders(); Appender appender = logger2AppendersMap.get(name2); addAppender(logger, appender); + context.updateLoggers(); } public static void addAppender(Logger logger, Appender appender) { + if (appender == null) + return; LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); + if (loggerConfig == null) + return; + + Level level = loggerConfig.getLevel(); + + config.addAppender(appender); loggerConfig.addAppender(appender, null, null); + + context.updateLoggers(); } public static void addAppenderToRootLogger(Appender appender) diff --git a/src/jalview/util/MapList.java b/src/jalview/util/MapList.java index 8efe42b..0f3fc2e 100644 --- a/src/jalview/util/MapList.java +++ b/src/jalview/util/MapList.java @@ -309,7 +309,7 @@ public class MapList if (range.length != 2) { // throw new IllegalArgumentException(range); - Cache.log.error("Invalid format for fromRange " + Cache.error("Invalid format for fromRange " + Arrays.toString(range) + " may cause errors"); } fromLowest = Math.min(fromLowest, Math.min(range[0], range[1])); @@ -323,7 +323,7 @@ public class MapList if (range.length != 2) { // throw new IllegalArgumentException(range); - Cache.log.error("Invalid format for toRange " + Cache.error("Invalid format for toRange " + Arrays.toString(range) + " may cause errors"); } toLowest = Math.min(toLowest, Math.min(range[0], range[1])); diff --git a/src/jalview/util/MappingUtils.java b/src/jalview/util/MappingUtils.java index 590e1c5..298c006 100644 --- a/src/jalview/util/MappingUtils.java +++ b/src/jalview/util/MappingUtils.java @@ -80,7 +80,7 @@ public final class MappingUtils action = action.getUndoAction(); } // TODO write this - Cache.log.error("MappingUtils.mapCutOrPaste not yet implemented"); + Cache.error("MappingUtils.mapCutOrPaste not yet implemented"); } /** @@ -835,7 +835,7 @@ public final class MappingUtils { if (range.length % 2 != 0) { - Cache.log.error( + Cache.error( "Error unbalance start/end ranges: " + ranges.toString()); return 0; } @@ -991,7 +991,7 @@ public final class MappingUtils /* * not coded for [start1, end1, start2, end2, ...] */ - Cache.log.error( + Cache.error( "MappingUtils.removeEndPositions doesn't handle multiple ranges"); return; } @@ -1002,7 +1002,7 @@ public final class MappingUtils /* * not coded for a reverse strand range (end < start) */ - Cache.log.error( + Cache.error( "MappingUtils.removeEndPositions doesn't handle reverse strand"); return; } diff --git a/src/jalview/util/MessageManager.java b/src/jalview/util/MessageManager.java index c562d8d..acd4591 100644 --- a/src/jalview/util/MessageManager.java +++ b/src/jalview/util/MessageManager.java @@ -27,8 +27,7 @@ import java.util.ResourceBundle; import java.util.ResourceBundle.Control; import java.util.Set; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import jalview.log.JLoggerLog4j; /** * @@ -41,8 +40,7 @@ public class MessageManager { private static ResourceBundle rb; - // BH 2018 switched to org.apache.llog4j.Logger - private static Logger log = LogManager + private static JLoggerLog4j log = JLoggerLog4j .getLogger(MessageManager.class.getCanonicalName()); private static Locale loc; diff --git a/src/jalview/ws/AWSThread.java b/src/jalview/ws/AWSThread.java index 80918f9..ead413e 100644 --- a/src/jalview/ws/AWSThread.java +++ b/src/jalview/ws/AWSThread.java @@ -127,7 +127,7 @@ public abstract class AWSThread extends Thread throw (new Exception( "Timed out when communicating with server\nTry again later.\n")); } - jalview.bin.Cache.log.debug("Job " + j + " Result state " + Cache.debug("Job " + j + " Result state " + jobs[j].getState() + "(ServerError=" + jobs[j].isServerError() + ")"); } catch (Exception ex) @@ -137,7 +137,7 @@ public abstract class AWSThread extends Thread .formatMessage("info.server_exception", new Object[] { WebServiceName, ex.getMessage() })); // always output the exception's stack trace to the log - Cache.log.warn(WebServiceName + " job(" + jobs[j].jobnum + Cache.warn(WebServiceName + " job(" + jobs[j].jobnum + ") Server exception."); // todo: could limit trace to cause if this is a SOAPFaultException. ex.printStackTrace(); @@ -145,7 +145,7 @@ public abstract class AWSThread extends Thread if (jobs[j].allowedServerExceptions > 0) { jobs[j].allowedServerExceptions--; - Cache.log.debug("Sleeping after a server exception."); + Cache.debug("Sleeping after a server exception."); try { Thread.sleep(5000); @@ -155,7 +155,7 @@ public abstract class AWSThread extends Thread } else { - Cache.log.warn("Dropping job " + j + " " + jobs[j].jobId); + Cache.warn("Dropping job " + j + " " + jobs[j].jobId); jobs[j].subjobComplete = true; wsInfo.setStatus(jobs[j].jobnum, WebserviceInfo.STATE_STOPPED_SERVERERROR); @@ -167,7 +167,7 @@ public abstract class AWSThread extends Thread jobs[j].clearResponse(); // may contain out of date result data wsInfo.setStatus(jobs[j].jobnum, WebserviceInfo.STATE_STOPPED_ERROR); - Cache.log.error("Out of memory when retrieving Job " + j + Cache.error("Out of memory when retrieving Job " + j + " id:" + WsUrl + "/" + jobs[j].jobId, er); new jalview.gui.OOMWarning( "retrieving result for " + WebServiceName, er); @@ -185,7 +185,7 @@ public abstract class AWSThread extends Thread Thread.sleep(5000); } catch (InterruptedException e) { - Cache.log.debug("Interrupted sleep waiting for next job poll.", + Cache.debug("Interrupted sleep waiting for next job poll.", e); } // System.out.println("I'm alive "+alTitle); @@ -197,7 +197,7 @@ public abstract class AWSThread extends Thread } else { - Cache.log.debug( + Cache.debug( "WebServiceJob poll loop finished with no jobs created."); wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR); wsInfo.appendProgressText( diff --git a/src/jalview/ws/DBRefFetcher.java b/src/jalview/ws/DBRefFetcher.java index 67b44d7..899fffc 100644 --- a/src/jalview/ws/DBRefFetcher.java +++ b/src/jalview/ws/DBRefFetcher.java @@ -362,9 +362,9 @@ public class DBRefFetcher implements Runnable AlignmentI retrieved = null; try { - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug("Querying " + dbsource.getDbName() + Cache.debug("Querying " + dbsource.getDbName() + " with : '" + queryString.toString() + "'"); } retrieved = dbsource.getSequenceRecords(queryString.toString()); diff --git a/src/jalview/ws/dbsources/EmblFlatfileSource.java b/src/jalview/ws/dbsources/EmblFlatfileSource.java index 2058800..0141a95 100644 --- a/src/jalview/ws/dbsources/EmblFlatfileSource.java +++ b/src/jalview/ws/dbsources/EmblFlatfileSource.java @@ -105,7 +105,7 @@ public abstract class EmblFlatfileSource extends EbiFileRetrievedProxy if (al == null) { - Cache.log.error( + Cache.error( "No record found for '" + dbName + ":" + query + "'"); } } diff --git a/src/jalview/ws/dbsources/EmblXmlSource.java b/src/jalview/ws/dbsources/EmblXmlSource.java index 06cbb13..b3b99ca 100644 --- a/src/jalview/ws/dbsources/EmblXmlSource.java +++ b/src/jalview/ws/dbsources/EmblXmlSource.java @@ -658,7 +658,7 @@ public abstract class EmblXmlSource extends EbiFileRetrievedProxy return listToArray(ranges); } catch (ParseException e) { - Cache.log.warn( + Cache.warn( String.format("Not parsing inexact CDS location %s in ENA %s", location, accession)); return new int[] {}; diff --git a/src/jalview/ws/dbsources/Xfam.java b/src/jalview/ws/dbsources/Xfam.java index 9340f65..fd8512f 100644 --- a/src/jalview/ws/dbsources/Xfam.java +++ b/src/jalview/ws/dbsources/Xfam.java @@ -65,10 +65,7 @@ public abstract class Xfam extends DbSourceProxyImpl // TODO: trap HTTP 404 exceptions and return null String xfamUrl = getURL(queries); - if (Cache.log != null) - { - Cache.log.debug("XFAM URL for retrieval is: " + xfamUrl); - } + Cache.debug("XFAM URL for retrieval is: " + xfamUrl); AlignmentI rcds = new FormatAdapter().readFile(xfamUrl, DataSourceType.URL, FileFormat.Stockholm); diff --git a/src/jalview/ws/jws1/Discoverer.java b/src/jalview/ws/jws1/Discoverer.java index bee9fad..9f11064 100644 --- a/src/jalview/ws/jws1/Discoverer.java +++ b/src/jalview/ws/jws1/Discoverer.java @@ -20,6 +20,7 @@ */ package jalview.ws.jws1; +import jalview.bin.Cache; import jalview.gui.JvOptionPane; import jalview.util.MessageManager; @@ -98,7 +99,7 @@ public class Discoverer implements Runnable // timeout } catch (Exception ex) { - jalview.bin.Cache.log.error( + Cache.error( "Serious! Service location failed\nfor URL :" + WsURL + "\n", ex); @@ -126,7 +127,7 @@ public class Discoverer implements Runnable static private Vector getDiscoveryURLS() { Vector urls = new Vector<>(); - String RootServiceURLs = jalview.bin.Cache.getDefault("DISCOVERY_URLS", + String RootServiceURLs = Cache.getDefault("DISCOVERY_URLS", "http://www.compbio.dundee.ac.uk/JalviewWS/services/ServiceRegistry"); try @@ -144,23 +145,21 @@ public class Discoverer implements Runnable } else { - jalview.bin.Cache.log - .info("Ignoring duplicate url in DISCOVERY_URLS list"); + Cache.info("Ignoring duplicate url in DISCOVERY_URLS list"); } } catch (Exception ex) { - jalview.bin.Cache.log - .warn("Problem whilst trying to make a URL from '" + Cache.warn("Problem whilst trying to make a URL from '" + ((url != null) ? url : "") + "'"); - jalview.bin.Cache.log.warn( + Cache.warn( "This was probably due to a malformed comma separated list" + " in the DISCOVERY_URLS entry of $(HOME)/.jalview_properties)"); - jalview.bin.Cache.log.debug("Exception was ", ex); + Cache.debug("Exception was ", ex); } } } catch (Exception ex) { - jalview.bin.Cache.log.warn( + Cache.warn( "Error parsing comma separated list of urls in DISCOVERY_URLS.", ex); } @@ -176,11 +175,10 @@ public class Discoverer implements Runnable */ static public void doDiscovery() { - jalview.bin.Cache.log - .debug("(Re)-Initialising the discovery URL list."); + Cache.debug("(Re)-Initialising the discovery URL list."); try { - reallyDiscoverServices = jalview.bin.Cache + reallyDiscoverServices = Cache .getDefault("DISCOVERY_START", false); if (reallyDiscoverServices) { @@ -188,7 +186,7 @@ public class Discoverer implements Runnable } else { - jalview.bin.Cache.log.debug("Setting default services"); + Cache.debug("Setting default services"); services = new Hashtable<>(); // Muscle, Clustal and JPred. ServiceHandle[] defServices = { new ServiceHandle("MsaWS", @@ -239,7 +237,7 @@ public class Discoverer implements Runnable ServiceHandles shs = null; try { - jalview.bin.Cache.log.debug("Discovering services using " + location); + Cache.debug("Discovering services using " + location); shs = locateWebService(location).getServices(); } catch (org.apache.axis.AxisFault f) { @@ -257,13 +255,13 @@ public class Discoverer implements Runnable } else { - jalview.bin.Cache.log.warn("No Discovery service at " + location); - jalview.bin.Cache.log.debug("Axis Fault", f); + Cache.warn("No Discovery service at " + location); + Cache.debug("Axis Fault", f); } } catch (Exception e) { - jalview.bin.Cache.log.warn("No Discovery service at " + location); - jalview.bin.Cache.log.debug("Discovery Service General Exception", e); + Cache.warn("No Discovery service at " + location); + Cache.debug("Discovery Service General Exception", e); } if ((shs != null) && shs.getServices().length > 0) { @@ -293,7 +291,7 @@ public class Discoverer implements Runnable { if (!cat.contains(sh[i])) { - jalview.bin.Cache.log.debug("A " + sh[i].getAbstractName() + Cache.debug("A " + sh[i].getAbstractName() + " service called " + sh[i].getName() + " exists at " + sh[i].getEndpointURL() + "\n"); if (!sscat.containsKey(sh[i].getAbstractName())) @@ -315,15 +313,14 @@ public class Discoverer implements Runnable disc_serv = new java.net.URL(sh[i].getEndpointURL()); if (!ServiceURLList.contains(disc_serv)) { - jalview.bin.Cache.log.debug( + Cache.debug( "Adding new discovery service at " + disc_serv); ServiceURLList.add(disc_serv); seenNewDiscovery = true; } } catch (Exception e) { - jalview.bin.Cache.log - .debug("Ignoring bad discovery service URL " + Cache.debug("Ignoring bad discovery service URL " + sh[i].getEndpointURL(), e); } } @@ -341,8 +338,7 @@ public class Discoverer implements Runnable int s_url = 0; if (ServiceURLList == null) { - jalview.bin.Cache.log - .debug("No service endpoints to use for service discovery."); + Cache.debug("No service endpoints to use for service discovery."); return; } while (s_url < ServiceURLList.size()) @@ -355,7 +351,7 @@ public class Discoverer implements Runnable } else { - jalview.bin.Cache.log.warn("No services at " + Cache.warn("No services at " + (ServiceURLList.get(s_url)) + " - check DISCOVERY_URLS property in .jalview_properties"); } diff --git a/src/jalview/ws/jws1/JPredClient.java b/src/jalview/ws/jws1/JPredClient.java index e9c2aea..d159b68 100644 --- a/src/jalview/ws/jws1/JPredClient.java +++ b/src/jalview/ws/jws1/JPredClient.java @@ -101,7 +101,7 @@ public class JPredClient extends WS1Client Jpred server = locateWebService(); if (server == null) { - Cache.log.warn("Couldn't find a Jpred webservice to invoke!"); + Cache.warn("Couldn't find a Jpred webservice to invoke!"); return; } SeqCigar[] msf = null; diff --git a/src/jalview/ws/jws1/JPredThread.java b/src/jalview/ws/jws1/JPredThread.java index 23d9eb0..9d8c11c 100644 --- a/src/jalview/ws/jws1/JPredThread.java +++ b/src/jalview/ws/jws1/JPredThread.java @@ -119,17 +119,17 @@ class JPredThread extends JWS1Thread implements WSClientI JpredResult result = (JpredResult) this.result; - Cache.log.debug("Parsing output from JNet job."); + Cache.debug("Parsing output from JNet job."); // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", // "File"); JPredFile prediction = new JPredFile(result.getPredfile(), DataSourceType.PASTE); SequenceI[] preds = prediction.getSeqsAsArray(); - Cache.log.debug("Got prediction profile."); + Cache.debug("Got prediction profile."); if ((this.msa != null) && (result.getAligfile() != null)) { - Cache.log.debug("Getting associated alignment."); + Cache.debug("Getting associated alignment."); // we ignore the returned alignment if we only predicted on a single // sequence FileFormatI format = new IdentifyFile() @@ -461,7 +461,7 @@ class JPredThread extends JWS1Thread implements WSClientI { job.setSubmitted(true); job.setSubjobComplete(false); - Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'"); + Cache.info(WsUrl + " Job Id '" + job.getJobId() + "'"); } } else @@ -484,7 +484,7 @@ class JPredThread extends JWS1Thread implements WSClientI "JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n" + e.getMessage() + "\n"); - jalview.bin.Cache.log.warn("Server Exception", e); + Cache.warn("Server Exception", e); } else { @@ -495,8 +495,7 @@ class JPredThread extends JWS1Thread implements WSClientI "info.failed_to_submit_prediction", new String[] { e.getMessage(), wsInfo.getProgressText() })); - jalview.bin.Cache.log - .debug("Failed Submission of job " + j.getJobnum(), e); + Cache.debug("Failed Submission of job " + j.getJobnum(), e); } j.setAllowedServerExceptions(-1); @@ -523,7 +522,7 @@ class JPredThread extends JWS1Thread implements WSClientI } catch (Exception ex) { - Cache.log.error( + Cache.error( "Unexpected exception when processing results for " + altitle, ex); wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR); @@ -577,9 +576,9 @@ class JPredThread extends JWS1Thread implements WSClientI msa = (j.msa != null) ? true : msa; try { - jalview.bin.Cache.log.debug("Parsing output of job " + jn); + Cache.debug("Parsing output of job " + jn); jobres = j.getResultSet(); - jalview.bin.Cache.log.debug("Finished parsing output."); + Cache.debug("Finished parsing output."); if (jobs.length == 1) { res = jobres; @@ -592,8 +591,7 @@ class JPredThread extends JWS1Thread implements WSClientI } } catch (Exception e) { - jalview.bin.Cache.log - .error("JNet Client: JPred Annotation Parse Error", e); + Cache.error("JNet Client: JPred Annotation Parse Error", e); wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR); wsInfo.appendProgressText(j.getJobnum(), @@ -652,7 +650,7 @@ class JPredThread extends JWS1Thread implements WSClientI } else { - Cache.log.info("Append results onto existing alignment."); + Cache.info("Append results onto existing alignment."); } } } diff --git a/src/jalview/ws/jws1/MsaWSThread.java b/src/jalview/ws/jws1/MsaWSThread.java index 006f014..9ad936b 100644 --- a/src/jalview/ws/jws1/MsaWSThread.java +++ b/src/jalview/ws/jws1/MsaWSThread.java @@ -410,7 +410,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI { cancelledMessage += ("\nProblems cancelling the job : Exception received...\n" + exc + "\n"); - Cache.log.warn( + Cache.warn( "Exception whilst cancelling " + jobs[job].getJobId(), exc); } @@ -453,9 +453,9 @@ class MsaWSThread extends JWS1Thread implements WSClientI MsaWSJob j = (MsaWSJob) job; if (j.isSubmitted()) { - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Tried to submit an already submitted job " + j.getJobId()); } return; @@ -542,7 +542,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI && jobs[j].hasResults()) { results++; - // if (Cache.log.isDebugEnabled()) + // if (Cache.isDebugEnabled()) // { // System.out.println("Job lob for job // "+jobs[j].getJobId()+":"+jobs[j].getJobnum()); @@ -571,7 +571,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI } catch (Exception ex) { - Cache.log.error( + Cache.error( "Unexpected exception when processing results for " + alTitle, ex); wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR); diff --git a/src/jalview/ws/jws1/SeqSearchWSClient.java b/src/jalview/ws/jws1/SeqSearchWSClient.java index 53338d3..eb60813 100644 --- a/src/jalview/ws/jws1/SeqSearchWSClient.java +++ b/src/jalview/ws/jws1/SeqSearchWSClient.java @@ -20,6 +20,7 @@ */ package jalview.ws.jws1; +import jalview.bin.Cache; import jalview.datamodel.AlignmentI; import jalview.datamodel.AlignmentView; import jalview.gui.AlignFrame; @@ -272,7 +273,7 @@ public class SeqSearchWSClient extends WS1Client .getSupportedDatabases(); } catch (Exception e) { - jalview.bin.Cache.log.warn( + Cache.warn( "Database list request failed, so disabling SeqSearch Service client " + sh.getName() + " at " + sh.getEndpointURL(), e); diff --git a/src/jalview/ws/jws1/SeqSearchWSThread.java b/src/jalview/ws/jws1/SeqSearchWSThread.java index 761b758..c0dcf67 100644 --- a/src/jalview/ws/jws1/SeqSearchWSThread.java +++ b/src/jalview/ws/jws1/SeqSearchWSThread.java @@ -425,7 +425,7 @@ class SeqSearchWSThread extends JWS1Thread implements WSClientI { cancelledMessage += ("\nProblems cancelling the job : Exception received...\n" + exc + "\n"); - Cache.log.warn( + Cache.warn( "Exception whilst cancelling " + jobs[job].getJobId(), exc); } @@ -469,9 +469,9 @@ class SeqSearchWSThread extends JWS1Thread implements WSClientI SeqSearchWSJob j = (SeqSearchWSJob) job; if (j.isSubmitted()) { - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Tried to submit an already submitted job " + j.getJobId()); } return; @@ -579,7 +579,7 @@ class SeqSearchWSThread extends JWS1Thread implements WSClientI } catch (Exception ex) { - Cache.log.error( + Cache.error( "Unexpected exception when processing results for " + alTitle, ex); wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR); diff --git a/src/jalview/ws/jws2/AADisorderClient.java b/src/jalview/ws/jws2/AADisorderClient.java index a1b8e7a..887a5d9 100644 --- a/src/jalview/ws/jws2/AADisorderClient.java +++ b/src/jalview/ws/jws2/AADisorderClient.java @@ -207,8 +207,7 @@ public class AADisorderClient extends JabawsCalcWorker scores = scoremanager.getAnnotationForSequence(seqId); } catch (Exception q) { - Cache.log - .info("Couldn't recover disorder prediction for sequence " + Cache.info("Couldn't recover disorder prediction for sequence " + seq.getName() + "(Prediction name was " + seqId + ")" + "\nSee http://issues.jalview.org/browse/JAL-1319 for one possible reason why disorder predictions might fail."); diff --git a/src/jalview/ws/jws2/AbstractJabaCalcWorker.java b/src/jalview/ws/jws2/AbstractJabaCalcWorker.java index dd64e77..5b3a69a 100644 --- a/src/jalview/ws/jws2/AbstractJabaCalcWorker.java +++ b/src/jalview/ws/jws2/AbstractJabaCalcWorker.java @@ -24,6 +24,7 @@ import jalview.analysis.AlignSeq; import jalview.analysis.SeqsetUtils; import jalview.api.AlignViewportI; import jalview.api.AlignmentViewPanel; +import jalview.bin.Cache; import jalview.datamodel.AlignmentAnnotation; import jalview.datamodel.AlignmentI; import jalview.datamodel.AnnotatedCollectionI; @@ -344,7 +345,7 @@ public abstract class AbstractJabaCalcWorker extends AlignCalcWorker } if (collectAnnotationResultsFor(rslt)) { - jalview.bin.Cache.log.debug("Updating result annotation from Job " + Cache.debug("Updating result annotation from Job " + rslt + " at " + service.getUri()); updateResultAnnotation(true); ap.adjustAnnotationHeight(); diff --git a/src/jalview/ws/jws2/JabaWsServerQuery.java b/src/jalview/ws/jws2/JabaWsServerQuery.java index d06c3f0..2af9101 100644 --- a/src/jalview/ws/jws2/JabaWsServerQuery.java +++ b/src/jalview/ws/jws2/JabaWsServerQuery.java @@ -212,16 +212,16 @@ public class JabaWsServerQuery implements Runnable else { jws2Discoverer.addInvalidServiceUrl(jwsserver); - Cache.log.warn("Ignoring invalid Jws2 service url " + jwsserver); + Cache.warn("Ignoring invalid Jws2 service url " + jwsserver); } } catch (Exception e) { e.printStackTrace(); - Cache.log.warn("Exception when discovering Jws2 services.", e); + Cache.warn("Exception when discovering Jws2 services.", e); jws2Discoverer.addInvalidServiceUrl(jwsserver); } catch (Error e) { - Cache.log.error("Exception when discovering Jws2 services.", e); + Cache.error("Exception when discovering Jws2 services.", e); jws2Discoverer.addInvalidServiceUrl(jwsserver); } running = false; diff --git a/src/jalview/ws/jws2/Jws2Client.java b/src/jalview/ws/jws2/Jws2Client.java index 71ba1b9..889f282 100644 --- a/src/jalview/ws/jws2/Jws2Client.java +++ b/src/jalview/ws/jws2/Jws2Client.java @@ -367,7 +367,7 @@ public abstract class Jws2Client extends jalview.ws.WSClient if (service != null && !fave.getService().hosturl.equals(service.hosturl)) { - Cache.log.debug("Changing AACon service to " + service.hosturl + Cache.debug("Changing AACon service to " + service.hosturl + " from " + fave.getService().hosturl); fave.setService(service); } @@ -389,7 +389,7 @@ public abstract class Jws2Client extends jalview.ws.WSClient if (!service.serviceType.toString() .equals(compbio.ws.client.Services.AAConWS.toString())) { - Cache.log.warn( + Cache.warn( "Ignoring invalid preferred service for AACon calculations (service type was " + service.serviceType + ")"); service = null; diff --git a/src/jalview/ws/jws2/Jws2Discoverer.java b/src/jalview/ws/jws2/Jws2Discoverer.java index 516a719..2fb8974 100644 --- a/src/jalview/ws/jws2/Jws2Discoverer.java +++ b/src/jalview/ws/jws2/Jws2Discoverer.java @@ -164,7 +164,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI { try { - Cache.log.debug( + Cache.debug( "Waiting around for old discovery thread to finish."); // wait around until old discoverer dies Thread.sleep(100); @@ -173,7 +173,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI } } aborted = false; - Cache.log.debug("Old discovery thread has finished."); + Cache.debug("Old discovery thread has finished."); } running = true; @@ -258,7 +258,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI } if (aborted) { - Cache.log.debug( + Cache.debug( "Aborting " + qrys.size() + " JABAWS discovery threads."); for (JabaWsServerQuery squery : qrys) { @@ -711,23 +711,23 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI } else { - Cache.log.warn("Ignoring duplicate url " + url + " in " + Cache.warn("Ignoring duplicate url " + url + " in " + JWS2HOSTURLS + " list"); } } catch (MalformedURLException ex) { - Cache.log.warn("Problem whilst trying to make a URL from '" + Cache.warn("Problem whilst trying to make a URL from '" + ((url != null) ? url : "") + "'"); - Cache.log.warn( + Cache.warn( "This was probably due to a malformed comma separated list" + " in the " + JWS2HOSTURLS + " entry of $(HOME)/.jalview_properties)"); - Cache.log.debug("Exception was ", ex); + Cache.debug("Exception was ", ex); } } } catch (Exception ex) { - Cache.log.warn("Error parsing comma separated list of urls in " + Cache.warn("Error parsing comma separated list of urls in " + JWS2HOSTURLS + " preference.", ex); } return urls; diff --git a/src/jalview/ws/jws2/MsaWSThread.java b/src/jalview/ws/jws2/MsaWSThread.java index db6e03f..8770b94 100644 --- a/src/jalview/ws/jws2/MsaWSThread.java +++ b/src/jalview/ws/jws2/MsaWSThread.java @@ -574,7 +574,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI { cancelledMessage += ("\nProblems cancelling the job : Exception received...\n" + exc + "\n"); - Cache.log.warn( + Cache.warn( "Exception whilst cancelling " + jobs[job].getJobId(), exc); } @@ -667,9 +667,9 @@ class MsaWSThread extends AWS2Thread implements WSClientI MsaWSJob j = (MsaWSJob) job; if (j.isSubmitted()) { - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { - Cache.log.debug( + Cache.debug( "Tried to submit an already submitted job " + j.getJobId()); } return; @@ -811,7 +811,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI } catch (Exception e) { - Cache.log.warn( + Cache.warn( "Exception when retrieving remaining Job progress data for job " + msjob.getJobId() + " on server " + WsUrl); e.printStackTrace(); @@ -835,7 +835,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI } } while (nunchanged > 0 && nexcept > 0); - if (Cache.log.isDebugEnabled()) + if (Cache.isDebugEnabled()) { System.out.println("Job Execution file for job: " + msjob.getJobId() + " on server " + WsUrl); @@ -850,7 +850,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI { // job has failed for some reason - probably due to invalid // parameters - Cache.log.debug( + Cache.debug( "Results not available for finished job - marking as broken job.", e); msjob.jobProgress.append( @@ -859,7 +859,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI msjob.setjobStatus(JobStatus.FAILED); } catch (Exception e) { - Cache.log.error("Couldn't get Alignment for job.", e); + Cache.error("Couldn't get Alignment for job.", e); // TODO: Increment count and retry ? msjob.setjobStatus(JobStatus.UNDEFINED); } @@ -887,7 +887,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI } catch (Exception ex) { - Cache.log.error( + Cache.error( "Unexpected exception when processing results for " + alTitle, ex); wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR); diff --git a/src/jalview/ws/rest/HttpResultSet.java b/src/jalview/ws/rest/HttpResultSet.java index 5bfe3b5..bff39c1 100644 --- a/src/jalview/ws/rest/HttpResultSet.java +++ b/src/jalview/ws/rest/HttpResultSet.java @@ -131,7 +131,7 @@ public class HttpResultSet extends FileParse implements AutoCloseable { error = true; errormessage = "Couldn't parse message from web service."; - Cache.log.warn("Failed to parse MIME multipart content", me); + Cache.warn("Failed to parse MIME multipart content", me); en.consumeContent(); } return new ParsePackedSet().getAlignment(ds, @@ -158,19 +158,19 @@ public class HttpResultSet extends FileParse implements AutoCloseable : en.getContentEncoding().getValue(); if (en.getContentType() != null) { - Cache.log.debug("Result Type: " + en.getContentType().toString()); + Cache.debug("Result Type: " + en.getContentType().toString()); } else { - Cache.log.debug("No Result Type Specified."); + Cache.debug("No Result Type Specified."); } if (enc == null || enc.length() < 1) { - Cache.log.debug("Assuming 'Default' Result Encoding."); + Cache.debug("Assuming 'Default' Result Encoding."); } else { - Cache.log.debug("Result Encoded as : " + enc); + Cache.debug("Result Encoded as : " + enc); } // attempt to identify file and construct an appropriate DataSource // identifier for it. @@ -184,7 +184,7 @@ public class HttpResultSet extends FileParse implements AutoCloseable : new InputStreamReader(en.getContent()); } catch (UnsupportedEncodingException e) { - Cache.log.error("Can't handle encoding '" + enc + Cache.error("Can't handle encoding '" + enc + "' for response from webservice.", e); en.consumeContent(); error = true; diff --git a/src/jalview/ws/rest/RestClient.java b/src/jalview/ws/rest/RestClient.java index a71b70d..fdab105 100644 --- a/src/jalview/ws/rest/RestClient.java +++ b/src/jalview/ws/rest/RestClient.java @@ -412,7 +412,7 @@ public class RestClient extends WSClient { for (RestServiceDescription descr : RestServiceDescription .parseDescriptions( - jalview.bin.Cache.getDefault(RSBS_SERVICES, + Cache.getDefault(RSBS_SERVICES, makeShmmrRestClient().service.toString()))) { services.add(descr.toString()); diff --git a/src/jalview/ws/rest/RestJobThread.java b/src/jalview/ws/rest/RestJobThread.java index 20b517b..1cb1bc2 100644 --- a/src/jalview/ws/rest/RestJobThread.java +++ b/src/jalview/ws/rest/RestJobThread.java @@ -268,7 +268,7 @@ public class RestJobThread extends AWSThread + "
See Console output for details."; rj.setAllowedServerExceptions(0);// unrecoverable; rj.error = true; - Cache.log.fatal("Unexpected REST Job " + getStage(stg) + Cache.fatal("Unexpected REST Job " + getStage(stg) + "exception for URL " + rj.rsd.postUrl); throw (he); } catch (IOException e) @@ -277,7 +277,7 @@ public class RestJobThread extends AWSThread + "Job.
Problematic url was " + request.getURI() + "
See Console output for details."; - Cache.log.warn("IO Exception for REST Job " + getStage(stg) + Cache.warn("IO Exception for REST Job " + getStage(stg) + "exception for URL " + rj.rsd.postUrl); throw (e); @@ -286,7 +286,7 @@ public class RestJobThread extends AWSThread { case 200: rj.running = false; - Cache.log.debug("Processing result set."); + Cache.debug("Processing result set."); processResultSet(rj, response, request); break; case 202: @@ -304,7 +304,7 @@ public class RestJobThread extends AWSThread { if (loc.length > 1) { - Cache.log.warn("Ignoring additional " + (loc.length - 1) + Cache.warn("Ignoring additional " + (loc.length - 1) + " location(s) provided in response header ( next one is '" + loc[1].getValue() + "' )"); } @@ -326,7 +326,7 @@ public class RestJobThread extends AWSThread default: // Some other response. Probably need to pop up the content in a window. // TODO: deal with all other HTTP response codes from server. - Cache.log.warn("Unhandled response status when " + getStage(stg) + Cache.warn("Unhandled response status when " + getStage(stg) + "for " + postUrl + ": " + response.getStatusLine()); rj.error = true; rj.setAllowedServerExceptions(0); @@ -340,7 +340,7 @@ public class RestJobThread extends AWSThread + "
Filtered response content below:
"); } catch (IOException e) { - Cache.log.debug("IOException when consuming unhandled response", + Cache.debug("IOException when consuming unhandled response", e); } ; @@ -447,7 +447,7 @@ public class RestJobThread extends AWSThread { job.setSubjobComplete(true); job.setAllowedServerExceptions(-1); - Cache.log.error("Exception when trying to start Rest Job.", ex); + Cache.error("Exception when trying to start Rest Job.", ex); } } @@ -456,7 +456,7 @@ public class RestJobThread extends AWSThread { // crazy users will see this message // TODO: finish this! and remove the message below! - Cache.log.warn("Rest job result parser is currently INCOMPLETE!"); + Cache.warn("Rest job result parser is currently INCOMPLETE!"); int validres = 0; for (RestJob rj : (RestJob[]) jobs) { @@ -465,22 +465,22 @@ public class RestJobThread extends AWSThread String ln = null; try { - Cache.log.debug("Parsing data for job " + rj.getJobId()); + Cache.debug("Parsing data for job " + rj.getJobId()); rj.parseResultSet(); if (rj.hasResults()) { validres++; } - Cache.log.debug("Finished parsing data for job " + rj.getJobId()); + Cache.debug("Finished parsing data for job " + rj.getJobId()); } catch (Error ex) { - Cache.log.warn( + Cache.warn( "Failed to finish parsing data for job " + rj.getJobId()); ex.printStackTrace(); } catch (Exception ex) { - Cache.log.warn( + Cache.warn( "Failed to finish parsing data for job " + rj.getJobId()); ex.printStackTrace(); } finally @@ -756,7 +756,7 @@ public class RestJobThread extends AWSThread { // TODO: decide if multiple multiple alignments returned by // non-vseparable services are allowed. - Cache.log.warn( + Cache.warn( "dealing with multiple alignment products returned by non-vertically separable service."); } // recover reference to last alignment created for this rest frame @@ -870,7 +870,7 @@ public class RestJobThread extends AWSThread } else { - Cache.log.warn( + Cache.warn( "Couldn't resolve original sequence for new sequence."); } } @@ -948,7 +948,7 @@ public class RestJobThread extends AWSThread grass = groupNames.get(alan[nrj][an].groupRef.getName()); if (grass == null) { - Cache.log.error( + Cache.error( "Couldn't relocate group referemce for group " + alan[nrj][an].groupRef.getName()); } @@ -999,7 +999,7 @@ public class RestJobThread extends AWSThread { // TODO: process each newick file, lifting over sequence refs to // current alignment, if necessary. - Cache.log.error( + Cache.error( "Tree recovery from restjob not yet implemented."); } } diff --git a/src/jalview/ws/seqfetcher/ASequenceFetcher.java b/src/jalview/ws/seqfetcher/ASequenceFetcher.java index 2a27cce..8f3f3b8 100644 --- a/src/jalview/ws/seqfetcher/ASequenceFetcher.java +++ b/src/jalview/ws/seqfetcher/ASequenceFetcher.java @@ -112,7 +112,7 @@ public class ASequenceFetcher return true; } } - Cache.log.warn("isFetchable doesn't know about '" + source + "'"); + Cache.warn("isFetchable doesn't know about '" + source + "'"); return false; } diff --git a/test/jalview/util/Log4jTest.java b/test/jalview/util/Log4jTest.java new file mode 100644 index 0000000..9aad697 --- /dev/null +++ b/test/jalview/util/Log4jTest.java @@ -0,0 +1,199 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) + * Copyright (C) $$Year-Rel$$ The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ +package jalview.util; + +import static org.testng.Assert.assertNotNull; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.concurrent.TimeUnit; + +import org.testng.Assert; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import io.github.classgraph.ClassGraph; +import io.github.classgraph.ScanResult; +import jalview.bin.Cache; + +public class Log4jTest +{ + private static final int TIMEOUT = 10; + + private static class Worker extends Thread + { + private final Process process; + + private BufferedReader outputReader; + + private BufferedReader errorReader; + + private boolean exited; + + private Worker(Process process) + { + this.process = process; + } + + @Override + public void run() + { + try + { + exited = process.waitFor(TIMEOUT, TimeUnit.SECONDS); + } catch (InterruptedException ignore) + { + return; + } + this.interrupt(); + this.process.destroy(); + } + + public BufferedReader getOutputReader() + { + return outputReader; + } + + public void setOutputReader(BufferedReader outputReader) + { + this.outputReader = outputReader; + } + + public BufferedReader getErrorReader() + { + return errorReader; + } + + public void setErrorReader(BufferedReader errorReader) + { + this.errorReader = errorReader; + } + } + + private static ClassGraph scanner = null; + + private static String classpath = null; + + private static String java_exe = null; + + public synchronized static String getClassPath() + { + if (scanner == null) + { + scanner = new ClassGraph(); + ScanResult scan = scanner.scan(); + classpath = scan.getClasspath(); + java_exe = System.getProperty("java.home") + File.separator + "bin" + + File.separator + "java"; + + } + while (classpath == null) + { + try + { + Thread.sleep(10); + } catch (InterruptedException x) + { + + } + } + return classpath; + } + + private Worker getJalviewDesktopRunner(String appArgs) + { + String classpath = getClassPath(); + String cmd = java_exe + " " + " -classpath " + classpath + " " + + " jalview.bin.Jalview " + " " + + "-props test/jalview/util/log4jTestProps.jvprops " + appArgs; + Process proc = null; + Worker worker = null; + try + { + proc = Runtime.getRuntime().exec(cmd); + } catch (Throwable e) + { + e.printStackTrace(); + } + if (proc != null) + { + BufferedReader outputReader = new BufferedReader( + new InputStreamReader(proc.getInputStream())); + BufferedReader errorReader = new BufferedReader( + new InputStreamReader(proc.getErrorStream())); + worker = new Worker(proc); + worker.start(); + worker.setOutputReader(outputReader); + worker.setErrorReader(errorReader); + } + return worker; + } + + @BeforeTest(alwaysRun = true) + public void initialize() + { + new Log4jTest(); + } + + @Test(groups = { "Functional" }) + public void testLog4j() + { + String appArgs = " -open examples/uniref50.fa -nosplash -nonews -noquestionnaire -nousagestats -nowebservicediscovery"; + + Worker worker = getJalviewDesktopRunner(appArgs); + assertNotNull(worker, "worker is null"); + + String ln = null; + int count = 0; + boolean logTestFound = false; + try + { + while ((ln = worker.getErrorReader().readLine()) != null) + { + if (++count > 500) + { + break; + } + if (ln.contains(Cache.LOGGING_TEST_MESSAGE)) + { + logTestFound = true; + break; + } + } + } catch (IOException e) + { + e.printStackTrace(); + } + if (worker != null && worker.exited == false) + { + worker.interrupt(); + worker.process.destroy(); + } + if (!logTestFound) + { + Assert.fail("Did not find Log4j Test message line '" + + Cache.LOGGING_TEST_MESSAGE + "'"); + } + } + +} diff --git a/test/jalview/util/log4jTestProps.jvprops b/test/jalview/util/log4jTestProps.jvprops new file mode 100644 index 0000000..c640dd1 --- /dev/null +++ b/test/jalview/util/log4jTestProps.jvprops @@ -0,0 +1,15 @@ +#---JalviewX Properties File--- +# HiDPI screen +SCREENGEOMETRY_WIDTH=3840 +SCREENGEOMETRY_HEIGHT=2160 +SCREEN_WIDTH=3000 +SCREEN_HEIGHT=2000 +USAGESTATS=false +STARTUP_FILE=examples/uniref50.fa +SHOW_STARTUP_FILE=false +FONT_STYLE=plain +FONT_SIZE=10 +ANTI_ALIAS=false +SHOW_JAVA_CONSOLE=false +DAS_REGISTRY_URL=http\://www.ebi.ac.uk/das-srv/registry/das/ +logs.Jalview.level=DEBUG -- 1.7.10.2