Merge branch 'develop' into releases/Release_2_11_2_Branch
authorJim Procter <j.procter@dundee.ac.uk>
Fri, 11 Feb 2022 17:28:01 +0000 (17:28 +0000)
committerJim Procter <j.procter@dundee.ac.uk>
Fri, 11 Feb 2022 17:28:01 +0000 (17:28 +0000)
193 files changed:
build.gradle
getdown/lib/FJVL_VERSION
getdown/lib/JVL_VERSION
getdown/lib/getdown-core.jar
getdown/lib/getdown-launcher-local.jar
getdown/lib/getdown-launcher.jar
getdown/src/getdown/ant/pom.xml
getdown/src/getdown/core/pom.xml
getdown/src/getdown/core/src/main/java/com/threerings/getdown/data/Application.java
getdown/src/getdown/core/src/main/java/jalview/bin/MemorySetting.java
getdown/src/getdown/core/src/main/java/jalview/util/ChannelProperties.java [new file with mode: 0644]
getdown/src/getdown/core/src/main/java/jalview/util/LaunchUtils.java [new file with mode: 0644]
getdown/src/getdown/core/src/main/java/jalview/util/StringUtils.java [new file with mode: 0644]
getdown/src/getdown/launcher/pom.xml
getdown/src/getdown/launcher/src/main/java/com/threerings/getdown/launcher/ProxyPanel.java
getdown/src/getdown/launcher/src/main/java/com/threerings/getdown/launcher/ProxyUtil.java
getdown/src/getdown/mvn_cmd
getdown/src/getdown/pom.xml
gradle.properties
help/help/html/logging.html
j11lib/getdown-core.jar
j11lib/log4j-1.2-api-2.17.0.jar [deleted file]
j11lib/log4j-api-2.17.1.jar [moved from j11lib/log4j-api-2.17.0.jar with 70% similarity]
j11lib/log4j-core-2.17.1.jar [moved from j8lib/log4j-core-2.17.0.jar with 78% similarity]
j11lib/log4j-slf4j18-impl-2.17.1.jar [moved from j8lib/log4j-slf4j18-impl-2.17.0.jar with 69% similarity]
j11lib/slf4j-log4j12-1.7.32.jar [deleted file]
j8lib/getdown-core.jar
j8lib/log4j-1.2-api-2.17.0.jar [deleted file]
j8lib/log4j-api-2.17.1.jar [moved from j8lib/log4j-api-2.17.0.jar with 70% similarity]
j8lib/log4j-core-2.17.1.jar [moved from j11lib/log4j-core-2.17.0.jar with 78% similarity]
j8lib/log4j-slf4j18-impl-2.17.1.jar [moved from j11lib/log4j-slf4j18-impl-2.17.0.jar with 69% similarity]
j8lib/slf4j-log4j12-1.7.32.jar [deleted file]
resources/lang/Messages.properties
resources/lang/Messages_es.properties
src/jalview/analysis/AlignmentUtils.java
src/jalview/analysis/CrossRef.java
src/jalview/analysis/GeneticCodes.java
src/jalview/analysis/PCA.java
src/jalview/analysis/TreeModel.java
src/jalview/bin/Cache.java
src/jalview/bin/Console.java [new file with mode: 0644]
src/jalview/bin/Jalview.java
src/jalview/bin/Launcher.java
src/jalview/bin/MemorySetting.java
src/jalview/datamodel/AlignedCodonFrame.java
src/jalview/datamodel/MappedFeatures.java
src/jalview/datamodel/SequenceFeature.java
src/jalview/ext/ensembl/EnsemblLookup.java
src/jalview/ext/ensembl/EnsemblSeqProxy.java
src/jalview/ext/htsjdk/VCFReader.java
src/jalview/ext/jmol/JalviewJmolBinding.java
src/jalview/ext/pymol/PymolManager.java
src/jalview/ext/rbvi/chimera/JalviewChimeraBinding.java
src/jalview/ext/so/SequenceOntology.java
src/jalview/fts/core/GFTSPanel.java
src/jalview/fts/service/alphafold/AlphafoldRestClient.java
src/jalview/fts/service/threedbeacons/TDBeaconsFTSPanel.java
src/jalview/gui/APQHandlers.java
src/jalview/gui/AlignFrame.java
src/jalview/gui/AlignViewport.java
src/jalview/gui/AlignmentPanel.java
src/jalview/gui/AppJmol.java
src/jalview/gui/AppJmolBinding.java
src/jalview/gui/BlogReader.java
src/jalview/gui/ChimeraViewFrame.java
src/jalview/gui/Console.java
src/jalview/gui/CrossRefAction.java
src/jalview/gui/CutAndPasteHtmlTransfer.java
src/jalview/gui/CutAndPasteTransfer.java
src/jalview/gui/Desktop.java
src/jalview/gui/FeatureSettings.java
src/jalview/gui/FeatureTypeSettings.java
src/jalview/gui/OOMWarning.java
src/jalview/gui/PCAPanel.java
src/jalview/gui/PopupMenu.java
src/jalview/gui/Preferences.java
src/jalview/gui/PromptUserConfig.java
src/jalview/gui/PymolBindingModel.java
src/jalview/gui/PymolViewer.java
src/jalview/gui/RotatableCanvas.java
src/jalview/gui/SeqPanel.java
src/jalview/gui/SequenceFetcher.java
src/jalview/gui/StructureChooser.java
src/jalview/gui/StructureViewer.java
src/jalview/gui/StructureViewerBase.java
src/jalview/gui/TreePanel.java
src/jalview/gui/UserQuestionnaireCheck.java
src/jalview/gui/VamsasApplication.java
src/jalview/gui/WsJobParameters.java
src/jalview/gui/WsParamSetManager.java
src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java
src/jalview/io/BackupFiles.java
src/jalview/io/BackupFilesPresetEntry.java
src/jalview/io/BioJsHTMLOutput.java
src/jalview/io/EMBLLikeFlatFile.java
src/jalview/io/EmblFlatFile.java
src/jalview/io/FileLoader.java
src/jalview/io/FileParse.java
src/jalview/io/FormatAdapter.java
src/jalview/io/HtmlSvgOutput.java
src/jalview/io/ModellerDescription.java
src/jalview/io/SequenceAnnotationReport.java
src/jalview/io/StockholmFile.java
src/jalview/io/VamsasAppDatastore.java
src/jalview/io/vamsas/DatastoreItem.java
src/jalview/io/vamsas/DatastoreRegistry.java
src/jalview/io/vamsas/Dbref.java
src/jalview/io/vamsas/Rangetype.java
src/jalview/io/vamsas/Sequencefeature.java
src/jalview/io/vamsas/Sequencemapping.java
src/jalview/io/vamsas/Tree.java
src/jalview/io/vcf/VCFLoader.java
src/jalview/javascript/MouseOverListener.java
src/jalview/javascript/log4j/Appender.java [deleted file]
src/jalview/javascript/log4j/ConsoleAppender.java [deleted file]
src/jalview/javascript/log4j/Layout.java [deleted file]
src/jalview/javascript/log4j/Level.java [deleted file]
src/jalview/javascript/log4j/Logger.java [deleted file]
src/jalview/javascript/log4j/Priority.java [deleted file]
src/jalview/javascript/log4j/SimpleLayout.java [deleted file]
src/jalview/javascript/log4j/WriterAppender.java [deleted file]
src/jalview/javascript/log4j/spi/LoggingEvent.java [deleted file]
src/jalview/javascript/log4j/spi/OptionHandler.java [deleted file]
src/jalview/jbgui/GAlignFrame.java
src/jalview/jbgui/GPreferences.java
src/jalview/jbgui/GWsPreferences.java
src/jalview/log/JLogger.java [new file with mode: 0644]
src/jalview/log/JLoggerI.java [new file with mode: 0644]
src/jalview/log/JLoggerLog4j.java [new file with mode: 0644]
src/jalview/log/JalviewAppender.java [moved from src/jalview/gui/JalviewAppender.java with 56% similarity]
src/jalview/project/Jalview2XML.java
src/jalview/structure/StructureSelectionManager.java
src/jalview/structures/models/AAStructureBindingModel.java
src/jalview/urls/UrlLinkTableModel.java
src/jalview/util/BrowserLauncher.java
src/jalview/util/ChannelProperties.java
src/jalview/util/LaunchUtils.java [new file with mode: 0644]
src/jalview/util/Log4j.java [new file with mode: 0644]
src/jalview/util/MapList.java
src/jalview/util/MappingUtils.java
src/jalview/util/MessageManager.java
src/jalview/util/StringUtils.java
src/jalview/ws/AWSThread.java
src/jalview/ws/DBRefFetcher.java
src/jalview/ws/dbsources/EmblFlatfileSource.java
src/jalview/ws/dbsources/EmblXmlSource.java
src/jalview/ws/dbsources/Xfam.java
src/jalview/ws/jws1/Discoverer.java
src/jalview/ws/jws1/JPredClient.java
src/jalview/ws/jws1/JPredThread.java
src/jalview/ws/jws1/MsaWSThread.java
src/jalview/ws/jws1/SeqSearchWSClient.java
src/jalview/ws/jws1/SeqSearchWSThread.java
src/jalview/ws/jws2/AADisorderClient.java
src/jalview/ws/jws2/AbstractJabaCalcWorker.java
src/jalview/ws/jws2/JabaWsServerQuery.java
src/jalview/ws/jws2/Jws2Client.java
src/jalview/ws/jws2/Jws2Discoverer.java
src/jalview/ws/jws2/MsaWSThread.java
src/jalview/ws/rest/HttpResultSet.java
src/jalview/ws/rest/RestClient.java
src/jalview/ws/rest/RestJobThread.java
src/jalview/ws/seqfetcher/ASequenceFetcher.java
test/jalview/analysis/CrossRefTest.java
test/jalview/bin/CommandLineOperations.java
test/jalview/bin/HiDPISettingTest2.java
test/jalview/datamodel/SequenceFeatureTest.java
test/jalview/gui/JAL1353bugdemo.java
test/jalview/gui/PopupMenuTest.java
test/jalview/io/EmblFlatFileTest.java
test/jalview/io/FileIOTester.java
test/jalview/io/GenBankFileTest.java
test/jalview/io/vcf/VCFLoaderTest.java
test/jalview/util/Log4jTest.java [new file with mode: 0644]
test/jalview/util/MapListTest.java
test/jalview/util/MappingUtilsTest.java
test/jalview/util/log4jTestProps.jvprops [new file with mode: 0644]
test/jalview/ws/dbsources/EmblXmlSourceTest.java
test/jalview/ws/gui/Jws2ParamView.java
test/jalview/ws/jabaws/DisorderAnnotExportImport.java
test/jalview/ws/jabaws/RNAStructExportImport.java
test/jalview/ws/jws2/ParameterUtilsTest.java
test/jalview/ws/rest/ShmmrRSBSService.java
test/jalview/ws/seqfetcher/DbRefFetcherTest.java
utils/channels/default/resources/channel.props
utils/install4j/auto_file_associations-i4j8.pl
utils/install4j/file_associations_auto-Info_plist.xml
utils/install4j/file_associations_auto-install4j8.xml
utils/install4j/install4j8_template.install4j
utils/install4j/jvl_file.icns [new file with mode: 0644]
utils/install4j/jvl_file.ico [new file with mode: 0644]
utils/install4j/jvl_file.png [new file with mode: 0644]
utils/install4j/jvl_file.svg [new file with mode: 0644]

index 17407a9..34a3461 100644 (file)
@@ -103,6 +103,7 @@ ext {
   // Import channel_properties
   channelDir = string("${jalviewDir}/${channel_properties_dir}/${propertiesChannelName}")
   channelGradleProperties = string("${channelDir}/channel_gradle.properties")
+  channelPropsFile = string("${channelDir}/${resource_dir}/${channel_props}")
   overrideProperties(channelGradleProperties, false)
   // local build environment properties
   // can be "projectDir/local.properties"
@@ -1511,6 +1512,12 @@ task getdownWebsite() {
     }
     getdownWebsiteResourceFilenames += "${getdownAppDistDir}/${getdown_build_properties}"
 
+    copy {
+      from channelPropsFile
+      into getdownWebsiteDir
+    }
+    getdownWebsiteResourceFilenames += file(channelPropsFile).getName()
+
     // set some getdown_txt_ properties then go through all properties looking for getdown_txt_...
     def props = project.properties.sort { it.key }
     if (getdownAltJavaMinVersion != null && getdownAltJavaMinVersion.length() > 0) {
@@ -1684,6 +1691,7 @@ task getdownWebsite() {
       from launchJvl
       from getdownLauncher
       from "${getdownWebsiteDir}/${getdown_build_properties}"
+      from "${getdownWebsiteDir}/${channel_props}"
       if (file(getdownLauncher).getName() != getdown_launcher) {
         rename(file(getdownLauncher).getName(), getdown_launcher)
       }
index df225c8..2cac91c 100644 (file)
@@ -1 +1 @@
-1.8.3-1.2.10_FJVL
+1.8.3-1.2.11_FJVL
index 6f6eed4..99f8359 100644 (file)
@@ -1 +1 @@
-1.8.3-1.2.10_JVL
+1.8.3-1.2.11_JVL
index dadce6e..a11a269 100644 (file)
Binary files a/getdown/lib/getdown-core.jar and b/getdown/lib/getdown-core.jar differ
index 88036f9..4ac9d5d 100644 (file)
Binary files a/getdown/lib/getdown-launcher-local.jar and b/getdown/lib/getdown-launcher-local.jar differ
index 4e2a98c..999c3fa 100644 (file)
Binary files a/getdown/lib/getdown-launcher.jar and b/getdown/lib/getdown-launcher.jar differ
index 9b26d50..e67984c 100644 (file)
@@ -4,7 +4,7 @@
   <parent>
     <groupId>com.threerings.getdown</groupId>
     <artifactId>getdown</artifactId>
-    <version>1.8.3-1.2.10_FJVL</version>
+    <version>1.8.3-1.2.11_FJVL</version>
   </parent>
 
   <artifactId>getdown-ant</artifactId>
index eb6f388..f909444 100644 (file)
@@ -4,7 +4,7 @@
   <parent>
     <groupId>com.threerings.getdown</groupId>
     <artifactId>getdown</artifactId>
-    <version>1.8.3-1.2.10_FJVL</version>
+    <version>1.8.3-1.2.11_FJVL</version>
   </parent>
 
   <artifactId>getdown-core</artifactId>
index 2022750..9deb5bc 100644 (file)
@@ -31,7 +31,7 @@ import java.util.zip.GZIPInputStream;
 
 import jalview.bin.HiDPISetting;
 import jalview.bin.MemorySetting;
-//import com.install4j.api.launcher.Variables;
+import jalview.util.LaunchUtils;
 
 import com.threerings.getdown.util.*;
 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
@@ -1181,6 +1181,17 @@ public class Application
             continue;
           }
         }
+
+        // use saved preferences if no cmdline args
+        LaunchUtils.loadChannelProps(getAppDir());
+        if (LaunchUtils.getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS)) {
+          if (jvmmempc == null) {
+            jvmmempc = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
+          }
+          if (jvmmemmax == null) {
+            jvmmemmax = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
+          }
+        }
         
         // add the memory setting from jvmmempc and jvmmemmax
         long maxMemLong = -1;
@@ -1253,7 +1264,9 @@ public class Application
         String[] sargs = args.toArray(new String[args.size()]);
         log.info("Running " + StringUtil.join(sargs, "\n  "));
 
-        return Runtime.getRuntime().exec(sargs, envp, getAppDir());
+        // don't set the working dir, leave it the same as the working dir of the invocation
+        //return Runtime.getRuntime().exec(sargs, envp, getAppDir());
+        return Runtime.getRuntime().exec(sargs, envp);
     }
 
     /**
index 5d7f14c..55e304d 100644 (file)
@@ -1,4 +1,6 @@
 /*
+
+  private static String ADJUSTMENT_MESSAGE = null;
  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
  * Copyright (C) $$Year-Rel$$ The Jalview Authors
  * 
@@ -31,6 +33,7 @@ package jalview.bin;
  * @author bsoares
  *
  */
+
 public class MemorySetting
 {
   public static final String MAX_HEAPSIZE_PERCENT_PROPERTY_NAME = "jvmmempc";
@@ -49,13 +52,33 @@ public class MemorySetting
 
   private static final long NOMEM_MAX_HEAPSIZE_GB_DEFAULT = 8;
 
+  public static final String NS = "MEMORY";
+
+  public static final String CUSTOMISED_SETTINGS = NS
+          + "_CUSTOMISED_SETTINGS";
+
+  public static final String MEMORY_JVMMEMPC = NS + "_"
+          + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.toUpperCase();
+
+  public static final String MEMORY_JVMMEMMAX = NS + "_"
+          + MAX_HEAPSIZE_PROPERTY_NAME.toUpperCase();
+
   protected static boolean logToClassChecked = false;
 
+  public static String memorySuffixes = "bkmgt"; // order of the suffixes is
+                                                 // important!
+
   public static long getMemorySetting()
   {
     return getMemorySetting(null, null);
   }
 
+  public static long getMemorySetting(String jvmmemmaxarg,
+          String jvmmempcarg)
+  {
+    return getMemorySetting(jvmmemmaxarg, jvmmempcarg, true, false);
+  }
+
   /**
    * Decide on appropriate memory setting for Jalview based on the two arguments
    * values: jvmmempc - the maximum percentage of total physical memory to
@@ -83,99 +106,66 @@ public class MemorySetting
    * @param jvmmempcarg
    *          Max percentage of physical memory to use. Defaults to "90".
    * 
+   * @param useProps
+   *          boolean to decide whether to look at System properties.
+   * 
    * @return The amount of memory (in bytes) to allocate to Jalview
    */
   public static long getMemorySetting(String jvmmemmaxarg,
-          String jvmmempcarg)
+          String jvmmempcarg, boolean useProps, boolean quiet)
   {
     // actual Xmx value-to-be
     long maxMemLong = -1;
+    clearAdjustmentMessage();
 
     // (absolute) jvmmaxmem setting, start with default
     long memmax = MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
-    if (jvmmemmaxarg == null)
+    if (jvmmemmaxarg == null && useProps)
     {
       jvmmemmaxarg = System.getProperty(MAX_HEAPSIZE_PROPERTY_NAME);
     }
     String jvmmemmax = jvmmemmaxarg;
     if (jvmmemmax != null && jvmmemmax.length() > 0)
     {
-      long multiplier = 1;
-      switch (jvmmemmax.toLowerCase().substring(jvmmemmax.length() - 1))
-      {
-      case "t":
-        multiplier = 1099511627776L; // 2^40
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "g":
-        multiplier = 1073741824; // 2^30
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "m":
-        multiplier = 1048576; // 2^20
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "k":
-        multiplier = 1024; // 2^10
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "b":
-        multiplier = 1; // 2^0
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      default:
-        break;
-      }
-
       // parse the arg
       try
       {
-        memmax = Long.parseLong(jvmmemmax);
+        memmax = memoryStringToLong(jvmmemmax);
+        if (memmax == 0)
+        {
+          throw (new NumberFormatException("Not allowing 0"));
+        }
       } catch (NumberFormatException e)
       {
         memmax = MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
-        System.out.println("MemorySetting Property '"
+        setAdjustmentMessage("MemorySetting Property '"
                 + MAX_HEAPSIZE_PROPERTY_NAME + "' (" + jvmmemmaxarg
-                + "') badly formatted, using default ("
-                + MAX_HEAPSIZE_GB_DEFAULT + "g).");
-      }
-
-      // apply multiplier if not too big (i.e. bigger than a long)
-      if (Long.MAX_VALUE / memmax < multiplier)
-      {
-        memmax = MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
-        System.out.println("MemorySetting Property '"
-                + MAX_HEAPSIZE_PROPERTY_NAME + "' (" + jvmmemmaxarg
-                + ") too big, using default (" + MAX_HEAPSIZE_GB_DEFAULT
-                + "g).");
-      }
-      else
-      {
-        memmax = multiplier * memmax;
+                + "') badly formatted or 0, using default ("
+                + MAX_HEAPSIZE_GB_DEFAULT + "g).", quiet);
       }
 
       // check at least minimum value (this accounts for negatives too)
       if (memmax < APPLICATION_MIN_MEMORY)
       {
         memmax = APPLICATION_MIN_MEMORY;
-        System.out.println("MemorySetting Property '"
+        setAdjustmentMessage("MemorySetting Property '"
                 + MAX_HEAPSIZE_PROPERTY_NAME + "' (" + jvmmemmaxarg
                 + ") too small, using minimum (" + APPLICATION_MIN_MEMORY
-                + ").");
+                + ").", quiet);
       }
 
     }
     else
     {
       // no need to warn if no setting
-      // System.out.println("MemorySetting Property '" + maxHeapSizeProperty
+      // adjustmentMessage("MemorySetting Property '" + maxHeapSizeProperty
       // + "' not
       // set.");
     }
 
     // get max percent of physical memory, starting with default
     float percent = MAX_HEAPSIZE_PERCENT_DEFAULT;
-    if (jvmmempcarg == null)
+    if (jvmmempcarg == null && useProps)
     {
       jvmmempcarg = System.getProperty(MAX_HEAPSIZE_PERCENT_PROPERTY_NAME);
     }
@@ -185,24 +175,24 @@ public class MemorySetting
     {
       if (jvmmempc != null)
       {
-        float trypercent = Float.parseFloat(jvmmempc);
-        if (0 < trypercent && trypercent <= 100f)
+        int trypercent = Integer.parseInt(jvmmempc);
+        if (0 <= trypercent && trypercent <= 100)
         {
           percent = trypercent;
         }
         else
         {
-          System.out.println("MemorySetting Property '"
+          setAdjustmentMessage("MemorySetting Property '"
                   + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME
-                  + "' should be in range 1..100. Using default " + percent
-                  + "%");
+                  + "' should be in range 0..100. Using default " + percent
+                  + "%", quiet);
         }
       }
     } catch (NumberFormatException e)
     {
-      System.out.println("MemorySetting property '"
+      setAdjustmentMessage("MemorySetting property '"
               + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' (" + jvmmempcarg
-              + ") badly formatted");
+              + ") badly formatted", quiet);
     }
 
     // catch everything in case of no com.sun.management.OperatingSystemMXBean
@@ -223,10 +213,10 @@ public class MemorySetting
         {
           mempc = physicalMem - LEAVE_FREE_MIN_MEMORY;
           reducedmempc = true;
-          System.out.println("MemorySetting Property '"
+          setAdjustmentMessage("MemorySetting Property '"
                   + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' (" + jvmmempcarg
                   + ") too large. Leaving free space for OS and reducing to ("
-                  + mempc + ").");
+                  + mempc + ").", quiet);
         }
 
         // check for minimum application memsize
@@ -234,16 +224,16 @@ public class MemorySetting
         {
           if (reducedmempc)
           {
-            System.out.println("Reduced MemorySetting (" + mempc
+            setAdjustmentMessage("Reduced MemorySetting (" + mempc
                     + ") too small. Increasing to application minimum ("
-                    + APPLICATION_MIN_MEMORY + ").");
+                    + APPLICATION_MIN_MEMORY + ").", quiet);
           }
           else
           {
-            System.out.println("MemorySetting Property '"
+            setAdjustmentMessage("MemorySetting Property '"
                     + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' ("
                     + jvmmempcarg + ") too small. Using minimum ("
-                    + APPLICATION_MIN_MEMORY + ").");
+                    + APPLICATION_MIN_MEMORY + ").", quiet);
           }
           mempc = APPLICATION_MIN_MEMORY;
         }
@@ -252,19 +242,21 @@ public class MemorySetting
       {
         // not enough memory for application, just try and grab what we can!
         mempc = physicalMem;
-        System.out.println(
+        setAdjustmentMessage(
                 "Not enough physical memory for application. Ignoring MemorySetting Property '"
                         + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' ("
                         + jvmmempcarg
                         + "). Using maximum memory available ("
-                        + physicalMem + ").");
+                        + physicalMem + ").",
+                quiet);
       }
 
     } catch (Throwable t)
     {
       memoryPercentError = true;
-      System.out.println(
-              "Problem calling GetMemory.getPhysicalMemory(). Likely to be problem with com.sun.management.OperatingSystemMXBean");
+      setAdjustmentMessage(
+              "Problem calling GetMemory.getPhysicalMemory(). Likely to be problem with com.sun.management.OperatingSystemMXBean",
+              quiet);
       t.printStackTrace();
     }
 
@@ -281,9 +273,10 @@ public class MemorySetting
                                                               // == null))
             && memmax > NOMEM_MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE)
     {
-      System.out.println(
+      setAdjustmentMessage(
               "Capping maximum memory to " + NOMEM_MAX_HEAPSIZE_GB_DEFAULT
-                      + "g due to failure to read physical memory size.");
+                      + "g due to failure to read physical memory size.",
+              quiet);
       memmax = NOMEM_MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
     }
 
@@ -299,4 +292,120 @@ public class MemorySetting
     return maxMemLong;
   }
 
+  public static boolean isValidMemoryString(String text)
+  {
+    if (text.length() > 0)
+    {
+      char lastChar = text.charAt(text.length() - 1);
+      char[] otherChars = text.substring(0, text.length() - 1)
+              .toCharArray();
+      for (char c : otherChars)
+      {
+        if (c < '0' || c > '9')
+        {
+          return false;
+        }
+      }
+      if ((lastChar < '0' || lastChar > '9') && memorySuffixes
+              .indexOf(Character.toLowerCase(lastChar)) == -1)
+      {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  public static long memoryStringToLong(String memString)
+          throws NumberFormatException
+  {
+    if (!isValidMemoryString(memString)) // not valid
+    {
+      throw (new NumberFormatException("Not a valid memory string"));
+    }
+    char suffix = Character
+            .toLowerCase(memString.charAt(memString.length() - 1));
+    if ('0' <= suffix && suffix <= '9') // no suffix
+    {
+      return Long.valueOf(memString);
+    }
+    if (memorySuffixes.indexOf(suffix) == -1) // suffix is unknown
+    {
+      return -1;
+    }
+
+    long multiplier = (long) Math.pow(2,
+            memorySuffixes.indexOf(suffix) * 10); // note order of suffixes in
+                                                  // memorySuffixes important
+                                                  // here!
+    // parse the arg. NumberFormatExceptions passed on to calling method
+    long mem = Long
+            .parseLong(memString.substring(0, memString.length() - 1));
+    if (mem == 0)
+    {
+      return 0;
+    }
+
+    // apply multiplier only if result is not too big (i.e. bigger than a long)
+    if (Long.MAX_VALUE / mem > multiplier)
+    {
+      return multiplier * mem;
+    }
+    else
+    {
+      // number too big for a Long. Limit to Long.MAX_VALUE
+      System.out.println("Memory parsing of '" + memString
+              + "' produces number too big.  Limiting to Long.MAX_VALUE="
+              + Long.MAX_VALUE);
+      return Long.MAX_VALUE;
+    }
+  }
+
+  public static String memoryLongToString(long mem)
+  {
+    return memoryLongToString(mem, "%.1f");
+  }
+
+  public static String memoryLongToString(long mem, String format)
+  {
+    int exponent = 0;
+    float num = mem;
+    char suffix = 'b';
+
+    for (int i = 0; i < memorySuffixes.length(); i++)
+    {
+      char s = Character.toUpperCase(memorySuffixes.charAt(i));
+      if (mem < (long) Math.pow(2, exponent + 10)
+              || i == memorySuffixes.length() - 1) // last suffix
+      {
+        suffix = s;
+        num = (float) (mem / Math.pow(2, exponent));
+        break;
+      }
+      exponent += 10;
+    }
+
+    return String.format(format, num) + suffix;
+  }
+
+  private static String ADJUSTMENT_MESSAGE = null;
+
+  private static void setAdjustmentMessage(String reason, boolean quiet)
+  {
+    ADJUSTMENT_MESSAGE = reason;
+    if (!quiet)
+    {
+      System.out.println(reason);
+    }
+  }
+
+  public static void clearAdjustmentMessage()
+  {
+    ADJUSTMENT_MESSAGE = null;
+  }
+
+  public static String getAdjustmentMessage()
+  {
+    return ADJUSTMENT_MESSAGE;
+  }
+
 }
\ No newline at end of file
diff --git a/getdown/src/getdown/core/src/main/java/jalview/util/ChannelProperties.java b/getdown/src/getdown/core/src/main/java/jalview/util/ChannelProperties.java
new file mode 100644 (file)
index 0000000..40f6110
--- /dev/null
@@ -0,0 +1,288 @@
+package jalview.util;
+
+import java.awt.Image;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.swing.ImageIcon;
+
+public class ChannelProperties
+{
+
+  public static final String CHANNEL_PROPERTIES_FILENAME = "channel.props";
+
+  private static Properties channelProps;
+
+  private static final Properties defaultProps;
+
+  private static Map<String, Image> imageMap = new HashMap<String, Image>();
+
+  private static Map<String, URL> urlMap = new HashMap<String, URL>();
+
+  private static final ArrayList<Image> iconList;
+
+  static
+  {
+    defaultProps = new Properties();
+    // these should be kept up to date, but in real life they should never
+    // actually be used anyway.
+    defaultProps.put("app_name", "Jalview");
+    defaultProps.put("banner", "/default_images/jalview_banner.png");
+    defaultProps.put("logo.16", "/default_images/jalview_logo-16.png");
+    defaultProps.put("logo.32", "/default_images/jalview_logo-32.png");
+    defaultProps.put("logo.38", "/default_images/jalview_logo-38.png");
+    defaultProps.put("logo.48", "/default_images/jalview_logo-48.png");
+    defaultProps.put("logo.64", "/default_images/jalview_logo-64.png");
+    defaultProps.put("logo.128", "/default_images/jalview_logo-128.png");
+    defaultProps.put("logo.256", "/default_images/jalview_logo-256.png");
+    defaultProps.put("logo.512", "/default_images/jalview_logo-512.png");
+    defaultProps.put("rotatable_logo.48",
+            "/default_images/rotatable_jalview_logo-38.png");
+    defaultProps.put("bg_logo.28", "/default_images/barton_group-28.png");
+    defaultProps.put("bg_logo.30", "/default_images/barton_group-30.png");
+    defaultProps.put("bg_logo.32", "/default_images/barton_group-32.png");
+    defaultProps.put("uod_banner.28", "/default_images/UoD_banner-28.png");
+    defaultProps.put("uod_banner.30", "/default_images/UoD_banner-30.png");
+    defaultProps.put("uod_banner.32", "/default_images/UoD_banner-32.png");
+    defaultProps.put("default_appbase",
+            "https://www.jalview.org/getdown/release/1.8");
+    defaultProps.put("preferences.filename", ".jalview_properties");
+
+    // load channel_properties
+    Properties tryChannelProps = new Properties();
+    URL channelPropsURL = ChannelProperties.class
+            .getResource("/" + CHANNEL_PROPERTIES_FILENAME);
+    if (channelPropsURL == null)
+    {
+      // complete failure of channel_properties, set all properties to defaults
+      System.err.println("Failed to find '/" + CHANNEL_PROPERTIES_FILENAME
+              + "' file at '"
+              + (channelPropsURL == null ? "null"
+                      : channelPropsURL.toString())
+              + "'. Using class defaultProps.");
+      tryChannelProps = defaultProps;
+    }
+    else
+    {
+      try
+      {
+        InputStream channelPropsIS = channelPropsURL.openStream();
+        tryChannelProps.load(channelPropsIS);
+        channelPropsIS.close();
+      } catch (IOException e)
+      {
+        System.err.println(e.getMessage());
+        // return false;
+      }
+    }
+    channelProps = tryChannelProps;
+
+    /*
+     * The following slight palava for caching an icon list is so that all sizes of icons
+     * are the same. i.e. if there are /any/ channel_properties icons to use, then _only_
+     * use those channel_properties icons, don't mix in class default icons for missing
+     * sizes.  If there are _no_ (usable) channel icons then we can use the class default icons.
+     */
+    iconList = new ArrayList<Image>();
+    List<String> sizes = Arrays.asList("16", "32", "48", "64", "128", "256",
+            "512");
+    for (String size : sizes)
+    {
+      Image logo = null;
+      // not using defaults or class props first time through
+      logo = ChannelProperties.getImage("logo." + size, null, false);
+      if (logo != null)
+      {
+        iconList.add(logo);
+      }
+    }
+    // now add the class defaults if there were no channel icons defined
+    if (iconList.size() == 0)
+    {
+      for (String size : sizes)
+      {
+        Image logo = null;
+        String path = defaultProps.getProperty("logo." + size);
+        URL imageURL = ChannelProperties.class.getResource(path);
+        ImageIcon imgIcon = imageURL == null ? null
+                : new ImageIcon(imageURL);
+        logo = imgIcon == null ? null : imgIcon.getImage();
+        if (logo != null)
+        {
+          iconList.add(logo);
+        }
+      }
+    }
+  }
+
+  protected static void loadProps(File dir)
+  {
+    File channelPropsFile = new File(dir, CHANNEL_PROPERTIES_FILENAME);
+    if (channelPropsFile.exists())
+    {
+      try
+      {
+        InputStream is = new FileInputStream(channelPropsFile);
+        channelProps.load(is);
+      } catch (FileNotFoundException e)
+      {
+        System.err.println(e.getMessage());
+      } catch (IOException e)
+      {
+        System.err.println(e.getMessage());
+      }
+    }
+  }
+
+  private static Properties channelProps()
+  {
+    return channelProps;
+  }
+
+  private static Map<String, Image> imageMap()
+  {
+    return imageMap;
+  }
+
+  private static Map<String, URL> urlMap()
+  {
+    return urlMap;
+  }
+
+  /*
+   * getProperty(key) will get property value from channel_properties for key.
+   * If no property for key is found, it will fall back to using the defaultProps defined for this class.
+   */
+  public static String getProperty(String key)
+  {
+    return getProperty(key, null, true);
+  }
+
+  /*
+   * getProperty(key, defaultVal) will get property value from channel_properties for key.
+   * If no property for key is found, it will return defaultVal and NOT fall back to the class defaultProps.
+   */
+  public static String getProperty(String key, String defaultVal)
+  {
+    return getProperty(key, defaultVal, false);
+  }
+
+  /*
+   * internal method.  note that setting useClassDefaultProps=true will ignore the provided defaultVal
+   */
+  private static String getProperty(String key, String defaultVal,
+          boolean useClassDefaultProps)
+  {
+    if (channelProps() != null)
+    {
+      if (channelProps().containsKey(key))
+      {
+        return channelProps().getProperty(key,
+                useClassDefaultProps ? defaultProps.getProperty(key)
+                        : defaultVal);
+      }
+      else
+      {
+        System.err.println("Failed to get channel property '" + key + "'");
+      }
+    }
+    return null;
+  }
+
+  /*
+   * getImage(key) returns the channel defined image for property key. If that is null (e.g. due to
+   * no defined channel image or the image file being corrupt/unusable/missing) it uses the image
+   * defined in defaultChannelProps
+   */
+  public static Image getImage(String key)
+  {
+    return getImage(key, null, true);
+  }
+
+  /*
+   * getImage(key, defaultImg) will get image associated with value from channel_properties for key.
+   * If no property or associated image for key is found (or is usable), it will return defaultImg
+   * and NOT fall back to the class defaultProps.
+   */
+  public static Image getImage(String key, Image defaultImg)
+  {
+    return getImage(key, defaultImg, false);
+  }
+
+  /*
+   * internal method.  note that setting useClassDefaultImage=true will ignore the provided defaultImg
+   */
+  private static Image getImage(String key, Image defaultImg,
+          boolean useClassDefaultImage)
+  {
+    Image img = null;
+    if (imageMap().containsKey(key))
+    {
+      img = imageMap().get(key);
+    }
+    // Catch a previously untried or failed load
+    if (img == null)
+    {
+      String path = getProperty(key, null, useClassDefaultImage);
+      if (path == null) // no channel property or class default property (if
+                        // requested)
+      {
+        return useClassDefaultImage ? null : defaultImg;
+      }
+
+      URL imageURL = ChannelProperties.class.getResource(path);
+      ImageIcon imgIcon = imageURL == null ? null : new ImageIcon(imageURL);
+      img = imgIcon == null ? null : imgIcon.getImage();
+      if (img == null)
+      {
+        System.err.println(
+                "Failed to load channel image " + key + "=" + path);
+        if (!useClassDefaultImage)
+        {
+          return defaultImg;
+        }
+      }
+      else
+      {
+        imageMap().put(key, img);
+        urlMap.put(key, imageURL);
+      }
+    }
+    return img;
+  }
+
+  /*
+   * Public method to get the URL object pointing to a cached image.
+   */
+  public static URL getImageURL(String key)
+  {
+    if (getImage(key) != null)
+    {
+      if (urlMap().containsKey(key))
+      {
+        return urlMap().getOrDefault(key, null);
+      }
+      System.err.println(
+              "Do not use getImageURL(key) before using getImage(key...)");
+    }
+    return null;
+  }
+
+  /*
+   * Get a List of Icon images of different sizes.
+   */
+  public static ArrayList<Image> getIconList()
+  {
+    return iconList;
+  }
+}
diff --git a/getdown/src/getdown/core/src/main/java/jalview/util/LaunchUtils.java b/getdown/src/getdown/core/src/main/java/jalview/util/LaunchUtils.java
new file mode 100644 (file)
index 0000000..3302dba
--- /dev/null
@@ -0,0 +1,56 @@
+package jalview.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Properties;
+
+public class LaunchUtils
+{
+
+  public static void loadChannelProps(File dir)
+  {
+    ChannelProperties.loadProps(dir);
+  }
+
+  private static Properties userPreferences = null;
+
+  public static String getUserPreference(String key)
+  {
+    if (userPreferences == null)
+    {
+      String channelPrefsFilename = ChannelProperties
+              .getProperty("preferences.filename");
+      if (channelPrefsFilename == null)
+      {
+        return null;
+      }
+      File propertiesFile = new File(System.getProperty("user.home"),
+              channelPrefsFilename);
+      if (!propertiesFile.exists())
+      {
+        return null;
+      }
+      try
+      {
+        userPreferences = new Properties();
+        userPreferences.load(new FileInputStream(propertiesFile));
+      } catch (FileNotFoundException e)
+      {
+        // didn't find user preferences file
+        return null;
+      } catch (IOException e)
+      {
+        System.err.println(e.getMessage());
+        return null;
+      }
+    }
+    return userPreferences.getProperty(key);
+  }
+
+  public static boolean getBooleanUserPreference(String key)
+  {
+    return Boolean.parseBoolean(getUserPreference(key));
+  }
+}
diff --git a/getdown/src/getdown/core/src/main/java/jalview/util/StringUtils.java b/getdown/src/getdown/core/src/main/java/jalview/util/StringUtils.java
new file mode 100644 (file)
index 0000000..d758395
--- /dev/null
@@ -0,0 +1,585 @@
+/*
+ * 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 <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
+package jalview.util;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+public class StringUtils
+{
+  private static final Pattern DELIMITERS_PATTERN = Pattern
+          .compile(".*='[^']*(?!')");
+
+  private static final char PERCENT = '%';
+
+  private static final boolean DEBUG = false;
+
+  /*
+   * URL encoded characters, indexed by char value
+   * e.g. urlEncodings['='] = urlEncodings[61] = "%3D"
+   */
+  private static String[] urlEncodings = new String[255];
+
+  /**
+   * Returns a new character array, after inserting characters into the given
+   * character array.
+   * 
+   * @param in
+   *          the character array to insert into
+   * @param position
+   *          the 0-based position for insertion
+   * @param count
+   *          the number of characters to insert
+   * @param ch
+   *          the character to insert
+   */
+  public static final char[] insertCharAt(char[] in, int position,
+          int count, char ch)
+  {
+    char[] tmp = new char[in.length + count];
+
+    if (position >= in.length)
+    {
+      System.arraycopy(in, 0, tmp, 0, in.length);
+      position = in.length;
+    }
+    else
+    {
+      System.arraycopy(in, 0, tmp, 0, position);
+    }
+
+    int index = position;
+    while (count > 0)
+    {
+      tmp[index++] = ch;
+      count--;
+    }
+
+    if (position < in.length)
+    {
+      System.arraycopy(in, position, tmp, index, in.length - position);
+    }
+
+    return tmp;
+  }
+
+  /**
+   * Delete
+   * 
+   * @param in
+   * @param from
+   * @param to
+   * @return
+   */
+  public static final char[] deleteChars(char[] in, int from, int to)
+  {
+    if (from >= in.length || from < 0)
+    {
+      return in;
+    }
+
+    char[] tmp;
+
+    if (to >= in.length)
+    {
+      tmp = new char[from];
+      System.arraycopy(in, 0, tmp, 0, from);
+      to = in.length;
+    }
+    else
+    {
+      tmp = new char[in.length - to + from];
+      System.arraycopy(in, 0, tmp, 0, from);
+      System.arraycopy(in, to, tmp, from, in.length - to);
+    }
+    return tmp;
+  }
+
+  /**
+   * Returns the last part of 'input' after the last occurrence of 'token'. For
+   * example to extract only the filename from a full path or URL.
+   * 
+   * @param input
+   * @param token
+   *          a delimiter which must be in regular expression format
+   * @return
+   */
+  public static String getLastToken(String input, String token)
+  {
+    if (input == null)
+    {
+      return null;
+    }
+    if (token == null)
+    {
+      return input;
+    }
+    String[] st = input.split(token);
+    return st[st.length - 1];
+  }
+
+  /**
+   * Parses the input string into components separated by the delimiter. Unlike
+   * String.split(), this method will ignore occurrences of the delimiter which
+   * are nested within single quotes in name-value pair values, e.g. a='b,c'.
+   * 
+   * @param input
+   * @param delimiter
+   * @return elements separated by separator
+   */
+  public static String[] separatorListToArray(String input,
+          String delimiter)
+  {
+    int seplen = delimiter.length();
+    if (input == null || input.equals("") || input.equals(delimiter))
+    {
+      return null;
+    }
+    List<String> jv = new ArrayList<>();
+    int cp = 0, pos, escape;
+    boolean wasescaped = false, wasquoted = false;
+    String lstitem = null;
+    while ((pos = input.indexOf(delimiter, cp)) >= cp)
+    {
+      escape = (pos > 0 && input.charAt(pos - 1) == '\\') ? -1 : 0;
+      if (wasescaped || wasquoted)
+      {
+        // append to previous pos
+        jv.set(jv.size() - 1, lstitem = lstitem + delimiter
+                + input.substring(cp, pos + escape));
+      }
+      else
+      {
+        jv.add(lstitem = input.substring(cp, pos + escape));
+      }
+      cp = pos + seplen;
+      wasescaped = escape == -1;
+      // last separator may be in an unmatched quote
+      wasquoted = DELIMITERS_PATTERN.matcher(lstitem).matches();
+    }
+    if (cp < input.length())
+    {
+      String c = input.substring(cp);
+      if (wasescaped || wasquoted)
+      {
+        // append final separator
+        jv.set(jv.size() - 1, lstitem + delimiter + c);
+      }
+      else
+      {
+        if (!c.equals(delimiter))
+        {
+          jv.add(c);
+        }
+      }
+    }
+    if (jv.size() > 0)
+    {
+      String[] v = jv.toArray(new String[jv.size()]);
+      jv.clear();
+      if (DEBUG)
+      {
+        System.err.println("Array from '" + delimiter
+                + "' separated List:\n" + v.length);
+        for (int i = 0; i < v.length; i++)
+        {
+          System.err.println("item " + i + " '" + v[i] + "'");
+        }
+      }
+      return v;
+    }
+    if (DEBUG)
+    {
+      System.err.println(
+              "Empty Array from '" + delimiter + "' separated List");
+    }
+    return null;
+  }
+
+  /**
+   * Returns a string which contains the list elements delimited by the
+   * separator. Null items are ignored. If the input is null or has length zero,
+   * a single delimiter is returned.
+   * 
+   * @param list
+   * @param separator
+   * @return concatenated string
+   */
+  public static String arrayToSeparatorList(String[] list, String separator)
+  {
+    StringBuffer v = new StringBuffer();
+    if (list != null && list.length > 0)
+    {
+      for (int i = 0, iSize = list.length; i < iSize; i++)
+      {
+        if (list[i] != null)
+        {
+          if (v.length() > 0)
+          {
+            v.append(separator);
+          }
+          // TODO - escape any separator values in list[i]
+          v.append(list[i]);
+        }
+      }
+      if (DEBUG)
+      {
+        System.err
+                .println("Returning '" + separator + "' separated List:\n");
+        System.err.println(v);
+      }
+      return v.toString();
+    }
+    if (DEBUG)
+    {
+      System.err.println(
+              "Returning empty '" + separator + "' separated List\n");
+    }
+    return "" + separator;
+  }
+
+  /**
+   * Converts a list to a string with a delimiter before each term except the
+   * first. Returns an empty string given a null or zero-length argument. This
+   * can be replaced with StringJoiner in Java 8.
+   * 
+   * @param terms
+   * @param delim
+   * @return
+   */
+  public static String listToDelimitedString(List<String> terms,
+          String delim)
+  {
+    StringBuilder sb = new StringBuilder(32);
+    if (terms != null && !terms.isEmpty())
+    {
+      boolean appended = false;
+      for (String term : terms)
+      {
+        if (appended)
+        {
+          sb.append(delim);
+        }
+        appended = true;
+        sb.append(term);
+      }
+    }
+    return sb.toString();
+  }
+
+  /**
+   * Convenience method to parse a string to an integer, returning 0 if the
+   * input is null or not a valid integer
+   * 
+   * @param s
+   * @return
+   */
+  public static int parseInt(String s)
+  {
+    int result = 0;
+    if (s != null && s.length() > 0)
+    {
+      try
+      {
+        result = Integer.parseInt(s);
+      } catch (NumberFormatException ex)
+      {
+      }
+    }
+    return result;
+  }
+
+  /**
+   * Compares two versions formatted as e.g. "3.4.5" and returns -1, 0 or 1 as
+   * the first version precedes, is equal to, or follows the second
+   * 
+   * @param v1
+   * @param v2
+   * @return
+   */
+  public static int compareVersions(String v1, String v2)
+  {
+    return compareVersions(v1, v2, null);
+  }
+
+  /**
+   * Compares two versions formatted as e.g. "3.4.5b1" and returns -1, 0 or 1 as
+   * the first version precedes, is equal to, or follows the second
+   * 
+   * @param v1
+   * @param v2
+   * @param pointSeparator
+   *          a string used to delimit point increments in sub-tokens of the
+   *          version
+   * @return
+   */
+  public static int compareVersions(String v1, String v2,
+          String pointSeparator)
+  {
+    if (v1 == null || v2 == null)
+    {
+      return 0;
+    }
+    String[] toks1 = v1.split("\\.");
+    String[] toks2 = v2.split("\\.");
+    int i = 0;
+    for (; i < toks1.length; i++)
+    {
+      if (i >= toks2.length)
+      {
+        /*
+         * extra tokens in v1
+         */
+        return 1;
+      }
+      String tok1 = toks1[i];
+      String tok2 = toks2[i];
+      if (pointSeparator != null)
+      {
+        /*
+         * convert e.g. 5b2 into decimal 5.2 for comparison purposes
+         */
+        tok1 = tok1.replace(pointSeparator, ".");
+        tok2 = tok2.replace(pointSeparator, ".");
+      }
+      try
+      {
+        float f1 = Float.valueOf(tok1);
+        float f2 = Float.valueOf(tok2);
+        int comp = Float.compare(f1, f2);
+        if (comp != 0)
+        {
+          return comp;
+        }
+      } catch (NumberFormatException e)
+      {
+        System.err
+                .println("Invalid version format found: " + e.getMessage());
+        return 0;
+      }
+    }
+
+    if (i < toks2.length)
+    {
+      /*
+       * extra tokens in v2 
+       */
+      return -1;
+    }
+
+    /*
+     * same length, all tokens match
+     */
+    return 0;
+  }
+
+  /**
+   * Converts the string to all lower-case except the first character which is
+   * upper-cased
+   * 
+   * @param s
+   * @return
+   */
+  public static String toSentenceCase(String s)
+  {
+    if (s == null)
+    {
+      return s;
+    }
+    if (s.length() <= 1)
+    {
+      return s.toUpperCase();
+    }
+    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
+  }
+
+  /**
+   * A helper method that strips off any leading or trailing html and body tags.
+   * If no html tag is found, then also html-encodes angle bracket characters.
+   * 
+   * @param text
+   * @return
+   */
+  public static String stripHtmlTags(String text)
+  {
+    if (text == null)
+    {
+      return null;
+    }
+    String tmp2up = text.toUpperCase();
+    int startTag = tmp2up.indexOf("<HTML>");
+    if (startTag > -1)
+    {
+      text = text.substring(startTag + 6);
+      tmp2up = tmp2up.substring(startTag + 6);
+    }
+    // is omission of "<BODY>" intentional here??
+    int endTag = tmp2up.indexOf("</BODY>");
+    if (endTag > -1)
+    {
+      text = text.substring(0, endTag);
+      tmp2up = tmp2up.substring(0, endTag);
+    }
+    endTag = tmp2up.indexOf("</HTML>");
+    if (endTag > -1)
+    {
+      text = text.substring(0, endTag);
+    }
+
+    if (startTag == -1 && (text.contains("<") || text.contains(">")))
+    {
+      text = text.replaceAll("<", "&lt;");
+      text = text.replaceAll(">", "&gt;");
+    }
+    return text;
+  }
+
+  /**
+   * Answers the input string with any occurrences of the 'encodeable'
+   * characters replaced by their URL encoding
+   * 
+   * @param s
+   * @param encodable
+   * @return
+   */
+  public static String urlEncode(String s, String encodable)
+  {
+    if (s == null || s.isEmpty())
+    {
+      return s;
+    }
+
+    /*
+     * do % encoding first, as otherwise it may double-encode!
+     */
+    if (encodable.indexOf(PERCENT) != -1)
+    {
+      s = urlEncode(s, PERCENT);
+    }
+
+    for (char c : encodable.toCharArray())
+    {
+      if (c != PERCENT)
+      {
+        s = urlEncode(s, c);
+      }
+    }
+    return s;
+  }
+
+  /**
+   * Answers the input string with any occurrences of {@code c} replaced with
+   * their url encoding. Answers the input string if it is unchanged.
+   * 
+   * @param s
+   * @param c
+   * @return
+   */
+  static String urlEncode(String s, char c)
+  {
+    String decoded = String.valueOf(c);
+    if (s.indexOf(decoded) != -1)
+    {
+      String encoded = getUrlEncoding(c);
+      if (!encoded.equals(decoded))
+      {
+        s = s.replace(decoded, encoded);
+      }
+    }
+    return s;
+  }
+
+  /**
+   * Answers the input string with any occurrences of the specified (unencoded)
+   * characters replaced by their URL decoding.
+   * <p>
+   * Example: {@code urlDecode("a%3Db%3Bc", "-;=,")} should answer
+   * {@code "a=b;c"}.
+   * 
+   * @param s
+   * @param encodable
+   * @return
+   */
+  public static String urlDecode(String s, String encodable)
+  {
+    if (s == null || s.isEmpty())
+    {
+      return s;
+    }
+
+    for (char c : encodable.toCharArray())
+    {
+      String encoded = getUrlEncoding(c);
+      if (s.indexOf(encoded) != -1)
+      {
+        String decoded = String.valueOf(c);
+        s = s.replace(encoded, decoded);
+      }
+    }
+    return s;
+  }
+
+  /**
+   * Does a lazy lookup of the url encoding of the given character, saving the
+   * value for repeat lookups
+   * 
+   * @param c
+   * @return
+   */
+  private static String getUrlEncoding(char c)
+  {
+    if (c < 0 || c >= urlEncodings.length)
+    {
+      return String.valueOf(c);
+    }
+
+    String enc = urlEncodings[c];
+    if (enc == null)
+    {
+      try
+      {
+        enc = urlEncodings[c] = URLEncoder.encode(String.valueOf(c),
+                "UTF-8");
+      } catch (UnsupportedEncodingException e)
+      {
+        enc = urlEncodings[c] = String.valueOf(c);
+      }
+    }
+    return enc;
+  }
+
+  public static int firstCharPosIgnoreCase(String text, String chars)
+  {
+    int min = text.length() + 1;
+    for (char c : chars.toLowerCase().toCharArray())
+    {
+      int i = text.toLowerCase().indexOf(c);
+      if (0 <= i && i < min)
+      {
+        min = i;
+      }
+    }
+    return min < text.length() + 1 ? min : -1;
+  }
+}
index b5e68f2..5284412 100644 (file)
@@ -4,7 +4,7 @@
   <parent>
     <groupId>com.threerings.getdown</groupId>
     <artifactId>getdown</artifactId>
-    <version>1.8.3-1.2.10_FJVL</version>
+    <version>1.8.3-1.2.11_FJVL</version>
   </parent>
 
   <artifactId>getdown-launcher</artifactId>
index 2178273..5d697df 100644 (file)
@@ -40,6 +40,12 @@ public final class ProxyPanel extends JPanel implements ActionListener
         _getdown = getdown;
         _msgs = msgs;
 
+        String[] hostPortAuthUser = ProxyUtil.jalviewProxyProperties(getdown._app);
+        String host = hostPortAuthUser[0];
+        String port = hostPortAuthUser[1];
+        boolean proxyAuth = Boolean.parseBoolean(hostPortAuthUser[2]);
+        String username = hostPortAuthUser[3];
+
         setLayout(new VGroupLayout());
         setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
         add(new SaneLabelField(get("m.configure_proxy")));
@@ -48,11 +54,13 @@ public final class ProxyPanel extends JPanel implements ActionListener
         JPanel row = new JPanel(new GridLayout());
         row.add(new SaneLabelField(get("m.proxy_host")), BorderLayout.WEST);
         row.add(_host = new SaneTextField());
+        _host.setText(host);
         add(row);
 
         row = new JPanel(new GridLayout());
         row.add(new SaneLabelField(get("m.proxy_port")), BorderLayout.WEST);
         row.add(_port = new SaneTextField());
+        _port.setText(port);
         add(row);
 
         add(new Spacer(5, 5));
@@ -60,20 +68,22 @@ public final class ProxyPanel extends JPanel implements ActionListener
         row = new JPanel(new GridLayout());
         row.add(new SaneLabelField(get("m.proxy_auth_required")), BorderLayout.WEST);
         _useAuth = new JCheckBox();
+        _useAuth.setSelected(proxyAuth);
         row.add(_useAuth);
         add(row);
 
         row = new JPanel(new GridLayout());
         row.add(new SaneLabelField(get("m.proxy_username")), BorderLayout.WEST);
         _username = new SaneTextField();
-        _username.setEnabled(false);
+        _username.setText(username);
+        _username.setEnabled(_useAuth.isSelected());
         row.add(_username);
         add(row);
 
         row = new JPanel(new GridLayout());
         row.add(new SaneLabelField(get("m.proxy_password")), BorderLayout.WEST);
         _password = new SanePasswordField();
-        _password.setEnabled(false);
+        _password.setEnabled(_useAuth.isSelected());
         row.add(_password);
         add(row);
 
index a36b5fa..cb51ca4 100644 (file)
@@ -6,8 +6,10 @@
 package com.threerings.getdown.launcher;
 
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.PrintStream;
 import java.net.Authenticator;
 import java.net.HttpURLConnection;
@@ -19,6 +21,8 @@ import java.net.URLConnection;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
+import jalview.util.LaunchUtils;
+
 import ca.beq.util.win32.registry.RegistryKey;
 import ca.beq.util.win32.registry.RegistryValue;
 import ca.beq.util.win32.registry.RootKey;
@@ -88,15 +92,43 @@ public class ProxyUtil {
             port = hostPort[1];
         }
 
+        // look in jalview_properties
+        String[] hostPortAuthUser = jalviewProxyProperties(app);
+        host = hostPortAuthUser[0];
+        port = hostPortAuthUser[1];
+        boolean proxyAuth = Boolean.parseBoolean(hostPortAuthUser[2]);
+        String username = hostPortAuthUser[3];
+
         if (StringUtil.isBlank(host)) {
             return false;
         }
 
         // yay, we found a proxy configuration, configure it in the app
-        initProxy(app, host, port, null, null);
+        initProxy(app, host, port, username, null);
         return true;
     }
 
+    public static String[] jalviewProxyProperties(Application app) {
+      String host = null;
+      String port = null;
+      boolean proxyAuth = false;
+      String username = null;
+      LaunchUtils.loadChannelProps(app.getAppDir());
+      if (LaunchUtils.getBooleanUserPreference("USE_PROXY")) {
+        host = LaunchUtils.getUserPreference("PROXY_SERVER_HTTPS");
+        port = LaunchUtils.getUserPreference("PROXY_PORT_HTTPS");
+        if (StringUtil.isBlank(host)) {
+          host = LaunchUtils.getUserPreference("PROXY_SERVER");
+          port = LaunchUtils.getUserPreference("PROXY_PORT");
+        }
+        proxyAuth = LaunchUtils.getBooleanUserPreference("PROXY_AUTH");
+        if (proxyAuth) {
+          username = LaunchUtils.getUserPreference("PROXY_AUTH_USERNAME");
+        }
+      }
+      return new String[]{ host, port, String.valueOf(proxyAuth), username };
+    }
+
     public static boolean canLoadWithoutProxy (URL rurl)
     {
         log.info("Testing whether proxy is needed, via: " + rurl);
@@ -179,6 +211,7 @@ public class ProxyUtil {
     public static void initProxy (Application app, String host, String port,
                                   String username, String password)
     {
+System.out.println("**** initProxy(app, '"+host+"', "+port+", '"+username+"', "+(password==null?"null":"*x"+password.length())+")");
         // check whether we have saved proxy credentials
         String appDir = app.getAppDir().getAbsolutePath();
         ServiceLoader<ProxyAuth> loader = ServiceLoader.load(ProxyAuth.class);
index 65e5fb9..4ffb086 100755 (executable)
@@ -3,7 +3,7 @@
 if [ x$JVLVERSION != x ]; then
   export VERSION=$JVLVERSION
 else
-  export VERSION=1.8.3-1.2.10_JVL
+  export VERSION=1.8.3-1.2.11_JVL
 fi
 
 if [ x${VERSION%_JVL} = x$VERSION ]; then
index 7a0fd27..61b1440 100644 (file)
@@ -10,7 +10,7 @@
   <groupId>com.threerings.getdown</groupId>
   <artifactId>getdown</artifactId>
   <packaging>pom</packaging>
-  <version>1.8.3-1.2.10_FJVL</version>
+  <version>1.8.3-1.2.11_FJVL</version>
 
   <name>getdown</name>
   <description>An application installer and updater.</description>
index f0c0d9e..8eec281 100644 (file)
@@ -112,6 +112,7 @@ j11modules = com.sun.istack.runtime,com.sun.xml.bind,com.sun.xml.fastinfoset,com
 flexmark_css = utils/doc/github.css
 
 channel_properties_dir = utils/channels
+channel_props = channel.props
 
 install4j_home_dir = ~/buildtools/install4j8
 install4j_copyright_message = ...
@@ -222,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 
index 0975a47..4d7e2e3 100644 (file)
     Jalview.</p>
 
   <p>
+    Jalview logging will automatically scroll the text in the Java Console
+    but if you want to examine a particular part of the logs whilst logging
+    is still going on you can click on any part of the text area to
+    stop this behaviour.  A border should appear arround the
+    text area to signify that autoscroll has been turned off.  You can
+    toggle the autoscroll behaviour on and off by clicking again on the
+    text area.
+  </p>
+  <p>
     You can temporarily control the detail of what appears as output by
     selecting a <em>Log level</em> using the drop-down list at the
     bottom left of the console. There are several levels to choose from:
index dadce6e..a11a269 100644 (file)
Binary files a/j11lib/getdown-core.jar and b/j11lib/getdown-core.jar differ
diff --git a/j11lib/log4j-1.2-api-2.17.0.jar b/j11lib/log4j-1.2-api-2.17.0.jar
deleted file mode 100644 (file)
index a361ddc..0000000
Binary files a/j11lib/log4j-1.2-api-2.17.0.jar and /dev/null differ
similarity index 70%
rename from j11lib/log4j-api-2.17.0.jar
rename to j11lib/log4j-api-2.17.1.jar
index 77af535..1aae243 100644 (file)
Binary files a/j11lib/log4j-api-2.17.0.jar and b/j11lib/log4j-api-2.17.1.jar differ
similarity index 78%
rename from j8lib/log4j-core-2.17.0.jar
rename to j11lib/log4j-core-2.17.1.jar
index 256ff3d..4682527 100644 (file)
Binary files a/j8lib/log4j-core-2.17.0.jar and b/j11lib/log4j-core-2.17.1.jar differ
similarity index 69%
rename from j8lib/log4j-slf4j18-impl-2.17.0.jar
rename to j11lib/log4j-slf4j18-impl-2.17.1.jar
index 43b077b..a2bce46 100644 (file)
Binary files a/j8lib/log4j-slf4j18-impl-2.17.0.jar and b/j11lib/log4j-slf4j18-impl-2.17.1.jar differ
diff --git a/j11lib/slf4j-log4j12-1.7.32.jar b/j11lib/slf4j-log4j12-1.7.32.jar
deleted file mode 100644 (file)
index 4b0e8b7..0000000
Binary files a/j11lib/slf4j-log4j12-1.7.32.jar and /dev/null differ
index dadce6e..a11a269 100644 (file)
Binary files a/j8lib/getdown-core.jar and b/j8lib/getdown-core.jar differ
diff --git a/j8lib/log4j-1.2-api-2.17.0.jar b/j8lib/log4j-1.2-api-2.17.0.jar
deleted file mode 100644 (file)
index a361ddc..0000000
Binary files a/j8lib/log4j-1.2-api-2.17.0.jar and /dev/null differ
similarity index 70%
rename from j8lib/log4j-api-2.17.0.jar
rename to j8lib/log4j-api-2.17.1.jar
index 77af535..1aae243 100644 (file)
Binary files a/j8lib/log4j-api-2.17.0.jar and b/j8lib/log4j-api-2.17.1.jar differ
similarity index 78%
rename from j11lib/log4j-core-2.17.0.jar
rename to j8lib/log4j-core-2.17.1.jar
index 256ff3d..4682527 100644 (file)
Binary files a/j11lib/log4j-core-2.17.0.jar and b/j8lib/log4j-core-2.17.1.jar differ
similarity index 69%
rename from j11lib/log4j-slf4j18-impl-2.17.0.jar
rename to j8lib/log4j-slf4j18-impl-2.17.1.jar
index 43b077b..a2bce46 100644 (file)
Binary files a/j11lib/log4j-slf4j18-impl-2.17.0.jar and b/j8lib/log4j-slf4j18-impl-2.17.1.jar differ
diff --git a/j8lib/slf4j-log4j12-1.7.32.jar b/j8lib/slf4j-log4j12-1.7.32.jar
deleted file mode 100644 (file)
index 4b0e8b7..0000000
Binary files a/j8lib/slf4j-log4j12-1.7.32.jar and /dev/null differ
index 9e492b2..b448b4c 100644 (file)
@@ -1399,3 +1399,14 @@ label.log_level = Log level
 label.log_level_tooltip = Temporarily set the log level for this console. The log level will revert to {0} when this Java console is closed.
 label.copy_to_clipboard = Copy to clipboard
 label.copy_to_clipboard_tooltip = Copy all of the log text in this console to the system clipboard
+label.startup = Startup
+label.memory = Memory
+label.customise_memory_settings = Customise maximum memory settings
+label.memory_setting_text = New memory settings will only come into effect the next time you start Jalview
+label.maximum_memory_used = Maximum memory limited to both
+label.percent_of_physical_memory = Maximum percent of physical memory
+label.maximum_memory = Maximum absolute memory
+label.maximum_memory_tooltip = Enter memory as an integer number optionally followed by 'b', 'k', 'm', 'g' or 't'
+label.adjustments_for_this_computer = Adjustments for this computer
+label.memory_example_text = Maximum memory that would be used with these settings on this computer
+label.memory_example_tooltip = The memory allocated to Jalview is the smaller of the percentage of physical memory (default 90%) and the maximum absolute memory (default 32GB). If your computer's memory cannot be ascertained then the maximum absolute memory defaults to 8GB (if not customised).<br>Jalview will always try and reserve 512MB for the OS and at least 512MB for itself.
index 411643d..49e05e3 100644 (file)
@@ -1389,3 +1389,14 @@ label.log_level = Nivel del registro
 label.log_level_tooltip = Establezca temporalmente el nivel de registro para esta consola. El nivel de registro volverá a {0} cuando se cierre esta consola de Java.
 label.copy_to_clipboard = Copiar en el portapapeles
 label.copy_to_clipboard_tooltip = Copie todo el texto de registro en esta consola al portapapeles del sistema
+label.startup = Inicio
+label.memory = Memoria
+label.customise_memory_settings = Personalizar la configuración de memoria máxima
+label.memory_setting_text = La nueva configuración de memoria solo entrará en vigor la próxima vez que inicie Jalview
+label.maximum_memory_used = Memoria máxima limitada a ambos
+label.percent_of_physical_memory = Porcentaje máximo de memoria física
+label.maximum_memory = Memoria absoluta máxima
+label.maximum_memory_tooltip = Ingrese la memoria como un número entero seguido opcionalmente por 'b', 'k', 'm', 'g' o 't'
+label.adjustments_for_this_computer = Ajustes para esta computadora
+label.memory_example_text = Memoria máxima que se usaría con esta configuración en esta computadora
+label.memory_example_tooltip = La memoria asignada a Jalview es el menor entre el porcentaje de memoria física (predeterminado 90%) y la memoria absoluta máxima (predeterminado 32 GB). Si no se puede determinar la memoria de su computadora, la memoria absoluta máxima predeterminada es de 8 GB (si no está personalizada).<br>Jalview siempre intentará reservar 512 MB para el sistema operativo y al menos 512 MB para sí mismo.
index f95ff73..28f23b2 100644 (file)
@@ -38,7 +38,7 @@ import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.commands.RemoveGapColCommand;
 import jalview.datamodel.AlignedCodon;
 import jalview.datamodel.AlignedCodonFrame;
@@ -2056,7 +2056,7 @@ public class AlignmentUtils
           }
           else
           {
-            Cache.log.error(
+            Console.error(
                     "JAL-2154 regression: warning - found (and ignored) a duplicate CDS sequence:" + mtch.toString());
           }
         }
index c54357e..1783f37 100644 (file)
@@ -443,6 +443,11 @@ public class CrossRef
         addedXref |= importCrossRefSeq(cf, newDsSeqs, doNotAdd, dss,
                 retrievedDss);
       }
+      // JBPNote: What assumptions are made for dbref structures on 
+      // retrieved sequences ?
+      // addedXref will be true means importCrossRefSeq found 
+      // sequences with dbrefs with mappings to sequences congruent with dss 
+
       if (!addedXref)
       {
         // try again, after looking for matching IDs
@@ -516,7 +521,9 @@ public class CrossRef
 
   /**
    * process sequence retrieved via a dbref on source sequence to resolve and
-   * transfer data
+   * transfer data JBPNote: as of 2022-02-03 - this assumes retrievedSequence
+   * has dbRefs with Mapping references to a sequence congruent with
+   * sourceSequence
    * 
    * @param cf
    * @param sourceSequence
@@ -535,10 +542,11 @@ public class CrossRef
     List<DBRefEntry> dbr = retrievedSequence.getDBRefs();
     if (dbr != null)
     {
-       for (int ib = 0, nb = dbr.size(); ib < nb; ib++)
+      for (int ib = 0, nb = dbr.size(); ib < nb; ib++)
       {
 
-       DBRefEntry dbref = dbr.get(ib);
+        DBRefEntry dbref = dbr.get(ib);
+        // matched will return null if the dbref has no map
         SequenceI matched = findInDataset(dbref);
         if (matched == sourceSequence)
         {
@@ -550,7 +558,7 @@ public class CrossRef
         Mapping map = dbref.getMap();
         if (map != null)
         {
-               SequenceI ms = map.getTo();
+          SequenceI ms = map.getTo();
           if (ms != null && map.getMap() != null)
           {
             if (ms == sourceSequence)
@@ -716,7 +724,7 @@ public class CrossRef
    * Returns null or the first sequence in the dataset which is identical to
    * xref.mapTo, and has a) a primary dbref matching xref, or if none found, the
    * first one with an ID source|xrefacc
-   * 
+   * JBPNote: Could refactor this to AlignmentI/DatasetI
    * @param xref
    *          with map and mapped-to sequence
    * @return
@@ -814,7 +822,7 @@ public class CrossRef
    * Updates any empty mappings in the cross-references with one to a compatible
    * retrieved sequence if found, and adds any new mappings to the
    * AlignedCodonFrame
-   * 
+   * JBPNote: TODO: this relies on sequence IDs like UNIPROT|ACCESSION - which do not always happen.
    * @param mapFrom
    * @param xrefs
    * @param retrieved
index 8d69b0b..a2ecdca 100644 (file)
@@ -21,9 +21,6 @@
 package jalview.analysis;
 
 import java.util.Locale;
-
-import jalview.bin.Cache;
-
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
@@ -33,6 +30,8 @@ import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.StringTokenizer;
 
+import jalview.bin.Console;
+
 /**
  * A singleton that provides instances of genetic code translation tables
  * 
@@ -162,7 +161,7 @@ public final class GeneticCodes
       }
     } catch (IOException | NullPointerException e)
     {
-      Cache.log.error(
+      Console.error(
               "Error reading genetic codes data file " + fileName + ": "
               + e.getMessage());
     }
@@ -217,7 +216,7 @@ public final class GeneticCodes
       }
     } catch (IOException e)
     {
-      Cache.log.error(
+      Console.error(
               "Error reading nucleotide ambiguity codes data file: "
                       + e.getMessage());
     }
@@ -294,7 +293,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);
+          Console.error("wrong data length in code table: " + line);
         }
         else
         {
index d51f00e..4a3cfec 100755 (executable)
@@ -22,7 +22,7 @@ package jalview.analysis;
 
 import jalview.api.analysis.ScoreModelI;
 import jalview.api.analysis.SimilarityParamsI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.Point;
 import jalview.math.MatrixI;
@@ -220,7 +220,7 @@ public class PCA implements Runnable
       eigenMatrix.tqli();
     } catch (Exception q)
     {
-      Cache.log.error("Error computing PCA:  " + q.getMessage());
+      Console.error("Error computing PCA:  " + q.getMessage());
       q.printStackTrace();
     }
   }
index a50634e..4d5e4b2 100644 (file)
@@ -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.");
     // }
index bde6362..4d1a453 100755 (executable)
@@ -47,20 +47,10 @@ import java.util.regex.Pattern;
 import javax.swing.LookAndFeel;
 import javax.swing.UIManager;
 
-import org.apache.log4j.ConsoleAppender;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.log4j.SimpleLayout;
-import org.apache.log4j.builders.appender.ConsoleAppenderBuilder;
-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.JLoggerLog4j;
 import jalview.schemes.ColourSchemeLoader;
 import jalview.schemes.ColourSchemes;
 import jalview.schemes.UserColourScheme;
@@ -281,7 +271,8 @@ public class Cache
   /**
    * Initialises the Jalview Application Log
    */
-  public static Logger log;
+
+  public final static String JALVIEW_LOGGER_NAME = "JalviewLogger";
 
   // save the proxy properties set at startup
   public final static String[] startupProxyProperties = {
@@ -326,50 +317,9 @@ public class Cache
 
   private final static String JS_PROPERTY_PREFIX = "jalview_";
 
-  public static void initLogger()
-  {
-    if (log != null)
-    {
-      return;
-    }
-    try
-    {
-      // configure the root logger to stderr
-      ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
-      AppenderComponentBuilder consoleApp = builder.newAppender("stderr", "Console");
-      builder.add(consoleApp);
-      Configurator.initialize(builder.build());
-      // log output
-      Logger laxis = Logger.getLogger("org.apache.axis");
-      jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
-
-      laxis.setLevel(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
-      org.apache.log4j.Logger.getRootLogger()
-              .setLevel(org.apache.log4j.Level.INFO);
-
-      jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
-              .getDefault("logs.Jalview.level", Level.INFO.toString())));
-      // laxis.addAppender(ap);
-      // lcastor.addAppender(ap);
-      // jalview.bin.Cache.log.addAppender(ap);
-      // Tell the user that debug is enabled
-      jalview.bin.Cache.log.debug(ChannelProperties.getProperty("app_name")
-              + " Debugging Output Follows.");
-    } catch (Exception ex)
-    {
-      System.err.println("Problems initializing the log4j system\n");
-      ex.printStackTrace(System.err);
-    }
-  }
-
   /**
-   * Loads properties from the given properties file. Any existing properties are
-   * first cleared.
+   * Loads properties from the given properties file. Any existing properties
+   * are first cleared.
    */
   public static void loadProperties(String propsFile)
   {
@@ -477,7 +427,7 @@ public class Cache
     default:
       String message = "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
               + proxyType;
-      Cache.warn(message);
+      Console.warn(message);
     }
 
     // LOAD THE AUTHORS FROM THE authors.props file
@@ -509,27 +459,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");
@@ -708,10 +658,11 @@ public class Cache
   }
 
   /**
-   * Gets Jalview application property of given key. Returns null if key not found
+   * Gets Jalview application property of given key. Returns null if key not
+   * found
    * 
    * @param key
-   *              Name of property
+   *          Name of property
    * 
    * @return Property value
    */
@@ -727,8 +678,8 @@ public class Cache
   }
 
   /**
-   * These methods are used when checking if the saved preference is different to
-   * the default setting
+   * These methods are used when checking if the saved preference is different
+   * to the default setting
    */
 
   public static boolean getDefault(String property, boolean def)
@@ -761,8 +712,8 @@ public class Cache
   }
 
   /**
-   * Answers the value of the given property, or the supplied default value if the
-   * property is not set
+   * Answers the value of the given property, or the supplied default value if
+   * the property is not set
    */
   public static String getDefault(String property, String def)
   {
@@ -774,9 +725,9 @@ public class Cache
    * Stores property in the file "HOME_DIR/.jalview_properties"
    * 
    * @param key
-   *              Name of object
+   *          Name of object
    * @param obj
-   *              String value of property
+   *          String value of property
    * 
    * @return previous value of property (or null)
    */
@@ -849,14 +800,11 @@ public class Cache
         if (jalview.jbgui.GDesktop.class.getClassLoader()
                 .loadClass("uk.ac.vamsas.client.VorbaId") != null)
         {
-          jalview.bin.Cache.log.debug(
-                  "Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
+          Console.debug("Found Vamsas Classes (uk.ac..vamsas.client.VorbaId can be loaded)");
           vamsasJarsArePresent = 1;
-          Logger lvclient = Logger.getLogger("uk.ac.vamsas");
-          lvclient.setLevel(Level.toLevel(Cache
-                  .getDefault("logs.Vamsas.Level", Level.INFO.toString())));
-
-          lvclient.addAppender(log.getAppender("JalviewLogger"));
+          JLoggerLog4j lvclient = JLoggerLog4j.getLogger("uk.ac.vamsas",
+                  Console.getCachedLogLevel("logs.Vamsas.Level"));
+          JLoggerLog4j.addAppender(lvclient, Console.log, JALVIEW_LOGGER_NAME);
           // Tell the user that debug is enabled
           lvclient.debug(ChannelProperties.getProperty("app_name")
                   + " Vamsas Client Debugging Output Follows.");
@@ -864,7 +812,7 @@ public class Cache
       } catch (Exception e)
       {
         vamsasJarsArePresent = 0;
-        jalview.bin.Cache.log.debug("Vamsas Classes are not present");
+        Console.debug("Vamsas Classes are not present");
       }
     }
     return (vamsasJarsArePresent > 0);
@@ -889,14 +837,11 @@ public class Cache
         if (Cache.class.getClassLoader()
                 .loadClass("groovy.lang.GroovyObject") != null)
         {
-          jalview.bin.Cache.log.debug(
-                  "Found Groovy (groovy.lang.GroovyObject can be loaded)");
+          Console.debug("Found Groovy (groovy.lang.GroovyObject can be loaded)");
           groovyJarsArePresent = 1;
-          Logger lgclient = Logger.getLogger("groovy");
-          lgclient.setLevel(Level.toLevel(Cache
-                  .getDefault("logs.Groovy.Level", Level.INFO.toString())));
-
-          lgclient.addAppender(log.getAppender("JalviewLogger"));
+          JLoggerLog4j lgclient = JLoggerLog4j.getLogger("groovy",
+                  Console.getCachedLogLevel("logs.Groovy.Level"));
+          JLoggerLog4j.addAppender(lgclient, Console.log, JALVIEW_LOGGER_NAME);
           // Tell the user that debug is enabled
           lgclient.debug(ChannelProperties.getProperty("app_name")
                   + " Groovy Client Debugging Output Follows.");
@@ -904,11 +849,11 @@ public class Cache
       } catch (Error e)
       {
         groovyJarsArePresent = 0;
-        jalview.bin.Cache.log.debug("Groovy Classes are not present", e);
+        Console.debug("Groovy Classes are not present", e);
       } catch (Exception e)
       {
         groovyJarsArePresent = 0;
-        jalview.bin.Cache.log.debug("Groovy Classes are not present");
+        Console.debug("Groovy Classes are not present");
       }
     }
     return (groovyJarsArePresent > 0);
@@ -942,8 +887,7 @@ public class Cache
                   .loadClass("com.boxysystems.jgoogleanalytics.FocusPoint");
         } catch (Exception e)
         {
-          log.debug(
-                  "com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
+          Console.debug("com.boxysystems.jgoogleanalytics package is not present - tracking not enabled.");
           tracker = null;
           jgoogleanalyticstracker = null;
           trackerfocus = null;
@@ -962,9 +906,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[]
@@ -985,57 +928,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);
-          }
+          Console.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();
-          }
+          Console.warn("Failed to initialise GoogleTracker for Jalview Desktop with version "
+                  + vrs, ex);
+        }
+        if (err != null)
+        {
+          Console.error("Whilst initing GoogleTracker for Jalview Desktop version "
+                  + vrs, err);
         }
       }
       else
       {
-        log.debug("Successfully initialised tracker.");
+        Console.debug("Successfully initialised tracker.");
       }
     }
   }
@@ -1057,8 +967,7 @@ public class Cache
     Color col = ColorUtils.parseColourString(colprop);
     if (col == null)
     {
-      log.warn("Couldn't parse '" + colprop + "' as a colour for "
-              + property);
+      Console.warn("Couldn't parse '" + colprop + "' as a colour for " + property);
     }
     return (col == null) ? defcolour : col;
   }
@@ -1164,7 +1073,7 @@ public class Cache
    * Loads in user colour schemes from files.
    * 
    * @param files
-   *                a '|'-delimited list of file paths
+   *          a '|'-delimited list of file paths
    */
   public static void initUserColourSchemes(String files)
   {
@@ -1239,14 +1148,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"));
@@ -1274,7 +1183,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);
@@ -1294,7 +1203,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)
@@ -1338,7 +1247,7 @@ public class Cache
                             ? " [" + startupProxyProperties[6] + "]"
                             : "");
 
-    Cache.debug(sb.toString());
+    Console.debug(sb.toString());
   }
 
   public static void setProxyPropertiesFromPreferences()
@@ -1364,7 +1273,7 @@ public class Cache
     case Cache.PROXYTYPE_NONE:
       if (!previousProxyType.equals(proxyType))
       {
-        Cache.log.info("Setting no proxy settings");
+        Console.info("Setting no proxy settings");
         Cache.setProxyProperties(null, null, null, null, null, null, null,
                 null, null);
       }
@@ -1372,7 +1281,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");
+      Console.info("Setting custom proxy settings");
       boolean proxyAuthSet = Cache.getDefault("PROXY_AUTH", false);
       Cache.setProxyProperties(Cache.getDefault("PROXY_SERVER", null),
               Cache.getDefault("PROXY_PORT", null),
@@ -1386,7 +1295,7 @@ public class Cache
               proxyAuthSet ? Cache.proxyAuthPassword : null, "localhost");
       break;
     default: // system proxy settings by default
-      Cache.log.info("Setting system proxy settings");
+      Console.info("Setting system proxy settings");
       Cache.resetProxyProperties();
     }
   }
@@ -1438,7 +1347,7 @@ public class Cache
         char[] displayHttpPw = new char[httpPassword == null ? 0
                 : httpPassword.length];
         Arrays.fill(displayHttpPw, '*');
-        Cache.debug("CACHE Proxy: setting new Authenticator with httpUser='"
+        Console.debug("CACHE Proxy: setting new Authenticator with httpUser='"
                 + httpUser + "' httpPassword='" + displayHttpPw + "'");
         if (!Platform.isJS())
         /* *
@@ -1488,7 +1397,7 @@ public class Cache
                             && getRequestingPort() == Integer
                                     .valueOf(httpPort))
                     {
-                      Cache.debug(
+                      Console.debug(
                               "AUTHENTICATOR returning PasswordAuthentication(\""
                                       + httpUser + "\", '"
                                       + new String(displayHttpPw) + "')");
@@ -1503,7 +1412,7 @@ public class Cache
                     {
                       char[] displayHttpsPw = new char[httpPassword.length];
                       Arrays.fill(displayHttpsPw, '*');
-                      Cache.debug(
+                      Console.debug(
                               "AUTHENTICATOR returning PasswordAuthentication(\""
                                       + httpsUser + "\", '" + displayHttpsPw
                                       + "'");
@@ -1512,15 +1421,15 @@ public class Cache
                     }
                   } catch (NumberFormatException e)
                   {
-                    Cache.error("Problem with proxy port values [http:"
+                    Console.error("Problem with proxy port values [http:"
                             + httpPort + ", https:" + httpsPort + "]");
                   }
-                  Cache.debug(
+                  Console.debug(
                           "AUTHENTICATOR after trying to get PasswordAuthentication");
                 }
               }
               // non proxy request
-              Cache.debug("AUTHENTICATOR returning null");
+              Console.debug("AUTHENTICATOR returning null");
               return null;
             }
           });
@@ -1528,13 +1437,13 @@ public class Cache
 
         // required to re-enable basic authentication (should be okay for a
         // local proxy)
-        Cache.debug(
+        Console.debug(
                 "AUTHENTICATOR setting property 'jdk.http.auth.tunneling.disabledSchemes' to \"\"");
         System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
       } catch (SecurityException e)
       {
-        Cache.error("Could not set default Authenticator");
-        Cache.debug(getStackTraceString(e));
+        Console.error("Could not set default Authenticator");
+        Console.debug(getStackTraceString(e));
       }
     }
     else
@@ -1552,13 +1461,13 @@ public class Cache
        * 
        */
       {
-        Cache.debug("AUTHENTICATOR setting default Authenticator to null");
+        Console.debug("AUTHENTICATOR setting default Authenticator to null");
         Authenticator.setDefault(null);
       }
     }
 
     // nonProxyHosts not currently configurable in Preferences
-    Cache.debug("AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
+    Console.debug("AUTHENTICATOR setting property 'http.nonProxyHosts' to \""
             + nonProxyHosts + "\"");
     setOrClearSystemProperty("http.nonProxyHosts", nonProxyHosts);
   }
@@ -1585,75 +1494,6 @@ public class Cache
     }
   }
 
-  public final static int TRACE = 10;
-
-  public final static int DEBUG = 20;
-
-  public final static int INFO = 30;
-
-  public final static int WARN = 40;
-
-  public final static int ERROR = 50;
-
-  public static boolean println(int level, String message)
-  {
-    if (Cache.log == null)
-    {
-      if (level >= WARN)
-        System.err.println(message);
-      else if (level >= INFO)
-        System.out.println(message);
-      // not printing debug or trace messages
-      return false;
-    }
-    if (level >= ERROR)
-    {
-      Cache.log.error(message);
-    }
-    else if (level >= WARN)
-    {
-      Cache.log.warn(message);
-    }
-    else if (level >= INFO)
-    {
-      Cache.log.info(message);
-    }
-    else if (level >= DEBUG)
-    {
-      Cache.log.debug(message);
-    }
-    else
-    {
-      Cache.log.trace(message);
-    }
-    return true;
-  }
-
-  public static void trace(String message)
-  {
-    println(TRACE, message);
-  }
-
-  public static void debug(String message)
-  {
-    println(DEBUG, message);
-  }
-
-  public static void info(String message)
-  {
-    println(INFO, message);
-  }
-
-  public static void warn(String message)
-  {
-    println(WARN, message);
-  }
-
-  public static void error(String message)
-  {
-    println(ERROR, message);
-  }
-
   /**
    * Getdown appbase methods
    */
diff --git a/src/jalview/bin/Console.java b/src/jalview/bin/Console.java
new file mode 100644 (file)
index 0000000..0b5a38a
--- /dev/null
@@ -0,0 +1,240 @@
+package jalview.bin;
+
+import jalview.log.JLogger;
+import jalview.log.JLoggerI.LogLevel;
+import jalview.log.JLoggerLog4j;
+import jalview.util.ChannelProperties;
+import jalview.util.Log4j;
+import jalview.util.Platform;
+
+public class Console
+{
+
+  public static JLoggerLog4j log;
+
+  public static void debug(String message, Throwable t)
+  {
+    if (Console.initLogger())
+    {
+      log.debug(message, t);
+    }
+    else
+    {
+      System.out.println(message);
+      t.printStackTrace();
+    }
+  
+  }
+
+  public static void info(String message)
+  {
+    if (Console.initLogger())
+    {
+      log.info(message, null);
+    }
+    else
+    {
+      System.out.println(message);
+    }
+  
+  }
+
+  public static void trace(String message, Throwable t)
+  {
+    if (Console.initLogger())
+    {
+      log.trace(message, t);
+    }
+    else
+    {
+      System.out.println(message);
+      t.printStackTrace();
+    }
+  }
+
+  public static void debug(String message)
+  {
+    if (Console.initLogger())
+    {
+      log.debug(message, null);
+    }
+    else
+    {
+      System.out.println(message);
+    }
+  
+  }
+
+  public static void info(String message, Throwable t)
+  {
+    if (Console.initLogger())
+    {
+      log.info(message, t);
+    }
+    else
+    {
+      System.out.println(message);
+      t.printStackTrace();
+    }
+  
+  }
+
+  public static void warn(String message)
+  {
+    if (Console.initLogger())
+    {
+      log.warn(message, null);
+    }
+    else
+    {
+      System.out.println(message);
+    }
+  
+  }
+
+  public static void trace(String message)
+  {
+    if (Console.initLogger())
+    {
+      log.trace(message, null);
+    }
+    else
+    {
+      System.out.println(message);
+    }
+  }
+
+  public static void warn(String message, Throwable t)
+  {
+    if (Console.initLogger())
+    {
+      log.warn(message, t);
+    }
+    else
+    {
+      System.out.println(message);
+      t.printStackTrace();
+    }
+  
+  }
+
+  public static void error(String message)
+  {
+    if (Console.initLogger())
+    {
+      log.error(message, null);
+    }
+    else
+    {
+      System.err.println(message);
+    }
+  
+  }
+
+  public static void error(String message, Throwable t)
+  {
+    if (Console.initLogger())
+    {
+      log.error(message, t);
+    }
+    else
+    {
+      System.err.println(message);
+      t.printStackTrace(System.err);
+    }
+  
+  }
+
+  public static void fatal(String message)
+  {
+    if (Console.initLogger())
+    {
+      log.fatal(message, null);
+    }
+    else
+    {
+      System.err.println(message);
+    }
+  
+  }
+
+  public static void fatal(String message, Throwable t)
+  {
+    if (Console.initLogger())
+    {
+      log.fatal(message, t);
+    }
+    else
+    {
+      System.err.println(message);
+      t.printStackTrace(System.err);
+    }
+  
+  }
+
+  public static boolean isDebugEnabled()
+  {
+    return log == null ? false : log.isDebugEnabled();
+  }
+
+  public static boolean isTraceEnabled()
+  {
+    return log == null ? false : log.isTraceEnabled();
+  }
+
+  public static JLogger.LogLevel getCachedLogLevel()
+  {
+    return Console.getCachedLogLevel(Cache.JALVIEWLOGLEVEL);
+  }
+
+  public static JLogger.LogLevel getCachedLogLevel(String key)
+  {
+    return JLogger.toLevel(Cache.getDefault(key, "INFO"));
+  }
+
+  public static boolean initLogger()
+  {
+    if (log != null)
+    {
+      return true;
+    }
+    try
+    {
+      JLogger.LogLevel cachedLevel = getCachedLogLevel();
+      if (!Platform.isJS())
+      {
+        Log4j.init(cachedLevel);
+      }
+      // log output
+      // 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(Cache.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(Console.LOGGING_TEST_MESSAGE);
+      // Tell the user that debug is enabled
+      debug(ChannelProperties.getProperty("app_name")
+              + " Debugging Output Follows.");
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+
+  public final static String LOGGING_TEST_MESSAGE = "Logging to STDERR";
+
+}
index 1ae1014..0c11808 100755 (executable)
@@ -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;
@@ -366,9 +365,10 @@ public class Jalview
     }
     System.setProperty("http.agent",
             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
+
     try
     {
-      Cache.initLogger();
+      Console.initLogger();
     } catch (NoClassDefFoundError error)
     {
       error.printStackTrace();
@@ -402,13 +402,13 @@ public class Jalview
         JalviewTaskbar.setTaskbar(this);
       } catch (Exception e)
       {
-        Cache.log.info("Cannot set Taskbar");
-        Cache.log.error(e.getMessage());
+        Console.info("Cannot set Taskbar");
+        Console.error(e.getMessage());
         // e.printStackTrace();
       } catch (Throwable t)
       {
-        Cache.log.info("Cannot set Taskbar");
-        Cache.log.error(t.getMessage());
+        Console.info("Cannot set Taskbar");
+        Console.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);
+            Console.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(
+              Console.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);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "system":
       lafSet = setSystemLookAndFeel();
       if (!lafSet)
       {
-        Cache.log.error("Could not set requested laf=" + laf);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "gtk":
       lafSet = setGtkLookAndFeel();
       if (!lafSet)
       {
-        Cache.log.error("Could not set requested laf=" + laf);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "metal":
       lafSet = setMetalLookAndFeel();
       if (!lafSet)
       {
-        Cache.log.error("Could not set requested laf=" + laf);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "nimbus":
       lafSet = setNimbusLookAndFeel();
       if (!lafSet)
       {
-        Cache.log.error("Could not set requested laf=" + laf);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "quaqua":
       lafSet = setQuaquaLookAndFeel();
       if (!lafSet)
       {
-        Cache.log.error("Could not set requested laf=" + laf);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "vaqua":
       lafSet = setVaquaLookAndFeel();
       if (!lafSet)
       {
-        Cache.log.error("Could not set requested laf=" + laf);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "mac":
       lafSet = setMacLookAndFeel();
       if (!lafSet)
       {
-        Cache.log.error("Could not set requested laf=" + laf);
+        Console.error("Could not set requested laf=" + laf);
       }
       break;
     case "none":
       break;
     default:
-      Cache.log.error("Requested laf=" + laf + " not implemented");
+      Console.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));
+      Console.error("Unexpected Look and Feel Exception");
+      Console.error(ex.getMessage());
+      Console.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));
+      Console.error("Unexpected Look and Feel Exception");
+      Console.error(ex.getMessage());
+      Console.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));
+      Console.error("Unexpected Look and Feel Exception");
+      Console.error(ex.getMessage());
+      Console.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.");
+                Console.debug("Initialising googletracker for usage stats.");
                 Cache.initGoogleTracker();
-                Cache.log.debug("Tracking enabled.");
+                Console.debug("Tracking enabled.");
               }
             }, new Runnable()
             {
               @Override
               public void run()
               {
-                Cache.log.debug("Not enabling Google Tracking.");
+                Console.debug("Not enabling Google Tracking.");
               }
             }, null, true);
     desktop.addDialogThread(prompter);
index e13f2dd..1ea17d6 100644 (file)
@@ -29,6 +29,7 @@ import java.util.ArrayList;
 import java.util.List;
 
 import jalview.util.ChannelProperties;
+import jalview.util.LaunchUtils;
 
 /**
  * A Launcher class for Jalview. This class is used to launch Jalview from the
@@ -106,6 +107,23 @@ public class Launcher
       }
     }
 
+    // use saved preferences if no cmdline args
+    boolean useCustomisedSettings = LaunchUtils
+            .getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS);
+    if (useCustomisedSettings)
+    {
+      if (jvmmempc == null)
+      {
+        jvmmempc = LaunchUtils
+                .getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
+      }
+      if (jvmmemmax == null)
+      {
+        jvmmemmax = LaunchUtils
+                .getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
+      }
+    }
+
     // add memory setting if not specified
     boolean memSet = false;
     boolean dockIcon = false;
@@ -228,7 +246,6 @@ public class Launcher
       e.printStackTrace();
     }
     // System.exit(0);
-
   }
 
 }
index 52f0c9e..56713b0 100644 (file)
@@ -1,4 +1,6 @@
 /*
+
+  private static String ADJUSTMENT_MESSAGE = null;
  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
  * Copyright (C) $$Year-Rel$$ The Jalview Authors
  * 
@@ -31,8 +33,6 @@ package jalview.bin;
  * @author bsoares
  *
  */
-import java.util.Locale;
-
 public class MemorySetting
 {
   public static final String MAX_HEAPSIZE_PERCENT_PROPERTY_NAME = "jvmmempc";
@@ -51,13 +51,33 @@ public class MemorySetting
 
   private static final long NOMEM_MAX_HEAPSIZE_GB_DEFAULT = 8;
 
+  public static final String NS = "MEMORY";
+
+  public static final String CUSTOMISED_SETTINGS = NS
+          + "_CUSTOMISED_SETTINGS";
+
+  public static final String MEMORY_JVMMEMPC = NS + "_"
+          + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.toUpperCase();
+
+  public static final String MEMORY_JVMMEMMAX = NS + "_"
+          + MAX_HEAPSIZE_PROPERTY_NAME.toUpperCase();
+
   protected static boolean logToClassChecked = false;
 
+  public static String memorySuffixes = "bkmgt"; // order of the suffixes is
+                                                 // important!
+
   public static long getMemorySetting()
   {
     return getMemorySetting(null, null);
   }
 
+  public static long getMemorySetting(String jvmmemmaxarg,
+          String jvmmempcarg)
+  {
+    return getMemorySetting(jvmmemmaxarg, jvmmempcarg, true, false);
+  }
+
   /**
    * Decide on appropriate memory setting for Jalview based on the two arguments
    * values: jvmmempc - the maximum percentage of total physical memory to
@@ -85,99 +105,66 @@ public class MemorySetting
    * @param jvmmempcarg
    *          Max percentage of physical memory to use. Defaults to "90".
    * 
+   * @param useProps
+   *          boolean to decide whether to look at System properties.
+   * 
    * @return The amount of memory (in bytes) to allocate to Jalview
    */
   public static long getMemorySetting(String jvmmemmaxarg,
-          String jvmmempcarg)
+          String jvmmempcarg, boolean useProps, boolean quiet)
   {
     // actual Xmx value-to-be
     long maxMemLong = -1;
+    clearAdjustmentMessage();
 
     // (absolute) jvmmaxmem setting, start with default
     long memmax = MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
-    if (jvmmemmaxarg == null)
+    if (jvmmemmaxarg == null && useProps)
     {
       jvmmemmaxarg = System.getProperty(MAX_HEAPSIZE_PROPERTY_NAME);
     }
     String jvmmemmax = jvmmemmaxarg;
     if (jvmmemmax != null && jvmmemmax.length() > 0)
     {
-      long multiplier = 1;
-      switch (jvmmemmax.toLowerCase(Locale.ROOT).substring(jvmmemmax.length() - 1))
-      {
-      case "t":
-        multiplier = 1099511627776L; // 2^40
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "g":
-        multiplier = 1073741824; // 2^30
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "m":
-        multiplier = 1048576; // 2^20
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "k":
-        multiplier = 1024; // 2^10
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      case "b":
-        multiplier = 1; // 2^0
-        jvmmemmax = jvmmemmax.substring(0, jvmmemmax.length() - 1);
-        break;
-      default:
-        break;
-      }
-
       // parse the arg
       try
       {
-        memmax = Long.parseLong(jvmmemmax);
+        memmax = memoryStringToLong(jvmmemmax);
+        if (memmax == 0)
+        {
+          throw (new NumberFormatException("Not allowing 0"));
+        }
       } catch (NumberFormatException e)
       {
         memmax = MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
-        System.out.println("MemorySetting Property '"
+        setAdjustmentMessage("MemorySetting Property '"
                 + MAX_HEAPSIZE_PROPERTY_NAME + "' (" + jvmmemmaxarg
-                + "') badly formatted, using default ("
-                + MAX_HEAPSIZE_GB_DEFAULT + "g).");
-      }
-
-      // apply multiplier if not too big (i.e. bigger than a long)
-      if (Long.MAX_VALUE / memmax < multiplier)
-      {
-        memmax = MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
-        System.out.println("MemorySetting Property '"
-                + MAX_HEAPSIZE_PROPERTY_NAME + "' (" + jvmmemmaxarg
-                + ") too big, using default (" + MAX_HEAPSIZE_GB_DEFAULT
-                + "g).");
-      }
-      else
-      {
-        memmax = multiplier * memmax;
+                + "') badly formatted or 0, using default ("
+                + MAX_HEAPSIZE_GB_DEFAULT + "g).", quiet);
       }
 
       // check at least minimum value (this accounts for negatives too)
       if (memmax < APPLICATION_MIN_MEMORY)
       {
         memmax = APPLICATION_MIN_MEMORY;
-        System.out.println("MemorySetting Property '"
+        setAdjustmentMessage("MemorySetting Property '"
                 + MAX_HEAPSIZE_PROPERTY_NAME + "' (" + jvmmemmaxarg
                 + ") too small, using minimum (" + APPLICATION_MIN_MEMORY
-                + ").");
+                + ").", quiet);
       }
 
     }
     else
     {
       // no need to warn if no setting
-      // System.out.println("MemorySetting Property '" + maxHeapSizeProperty
+      // adjustmentMessage("MemorySetting Property '" + maxHeapSizeProperty
       // + "' not
       // set.");
     }
 
     // get max percent of physical memory, starting with default
     float percent = MAX_HEAPSIZE_PERCENT_DEFAULT;
-    if (jvmmempcarg == null)
+    if (jvmmempcarg == null && useProps)
     {
       jvmmempcarg = System.getProperty(MAX_HEAPSIZE_PERCENT_PROPERTY_NAME);
     }
@@ -187,24 +174,24 @@ public class MemorySetting
     {
       if (jvmmempc != null)
       {
-        float trypercent = Float.parseFloat(jvmmempc);
-        if (0 < trypercent && trypercent <= 100f)
+        int trypercent = Integer.parseInt(jvmmempc);
+        if (0 <= trypercent && trypercent <= 100)
         {
           percent = trypercent;
         }
         else
         {
-          System.out.println("MemorySetting Property '"
+          setAdjustmentMessage("MemorySetting Property '"
                   + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME
-                  + "' should be in range 1..100. Using default " + percent
-                  + "%");
+                  + "' should be in range 0..100. Using default " + percent
+                  + "%", quiet);
         }
       }
     } catch (NumberFormatException e)
     {
-      System.out.println("MemorySetting property '"
+      setAdjustmentMessage("MemorySetting property '"
               + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' (" + jvmmempcarg
-              + ") badly formatted");
+              + ") badly formatted", quiet);
     }
 
     // catch everything in case of no com.sun.management.OperatingSystemMXBean
@@ -225,10 +212,10 @@ public class MemorySetting
         {
           mempc = physicalMem - LEAVE_FREE_MIN_MEMORY;
           reducedmempc = true;
-          System.out.println("MemorySetting Property '"
+          setAdjustmentMessage("MemorySetting Property '"
                   + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' (" + jvmmempcarg
                   + ") too large. Leaving free space for OS and reducing to ("
-                  + mempc + ").");
+                  + mempc + ").", quiet);
         }
 
         // check for minimum application memsize
@@ -236,16 +223,16 @@ public class MemorySetting
         {
           if (reducedmempc)
           {
-            System.out.println("Reduced MemorySetting (" + mempc
+            setAdjustmentMessage("Reduced MemorySetting (" + mempc
                     + ") too small. Increasing to application minimum ("
-                    + APPLICATION_MIN_MEMORY + ").");
+                    + APPLICATION_MIN_MEMORY + ").", quiet);
           }
           else
           {
-            System.out.println("MemorySetting Property '"
+            setAdjustmentMessage("MemorySetting Property '"
                     + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' ("
                     + jvmmempcarg + ") too small. Using minimum ("
-                    + APPLICATION_MIN_MEMORY + ").");
+                    + APPLICATION_MIN_MEMORY + ").", quiet);
           }
           mempc = APPLICATION_MIN_MEMORY;
         }
@@ -254,19 +241,21 @@ public class MemorySetting
       {
         // not enough memory for application, just try and grab what we can!
         mempc = physicalMem;
-        System.out.println(
+        setAdjustmentMessage(
                 "Not enough physical memory for application. Ignoring MemorySetting Property '"
                         + MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "' ("
                         + jvmmempcarg
                         + "). Using maximum memory available ("
-                        + physicalMem + ").");
+                        + physicalMem + ").",
+                quiet);
       }
 
     } catch (Throwable t)
     {
       memoryPercentError = true;
-      System.out.println(
-              "Problem calling GetMemory.getPhysicalMemory(). Likely to be problem with com.sun.management.OperatingSystemMXBean");
+      setAdjustmentMessage(
+              "Problem calling GetMemory.getPhysicalMemory(). Likely to be problem with com.sun.management.OperatingSystemMXBean",
+              quiet);
       t.printStackTrace();
     }
 
@@ -283,9 +272,10 @@ public class MemorySetting
                                                               // == null))
             && memmax > NOMEM_MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE)
     {
-      System.out.println(
+      setAdjustmentMessage(
               "Capping maximum memory to " + NOMEM_MAX_HEAPSIZE_GB_DEFAULT
-                      + "g due to failure to read physical memory size.");
+                      + "g due to failure to read physical memory size.",
+              quiet);
       memmax = NOMEM_MAX_HEAPSIZE_GB_DEFAULT * GIGABYTE;
     }
 
@@ -301,4 +291,120 @@ public class MemorySetting
     return maxMemLong;
   }
 
-}
\ No newline at end of file
+  public static boolean isValidMemoryString(String text)
+  {
+    if (text.length() > 0)
+    {
+      char lastChar = text.charAt(text.length() - 1);
+      char[] otherChars = text.substring(0, text.length() - 1)
+              .toCharArray();
+      for (char c : otherChars)
+      {
+        if (c < '0' || c > '9')
+        {
+          return false;
+        }
+      }
+      if ((lastChar < '0' || lastChar > '9') && memorySuffixes
+              .indexOf(Character.toLowerCase(lastChar)) == -1)
+      {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  public static long memoryStringToLong(String memString)
+          throws NumberFormatException
+  {
+    if (!isValidMemoryString(memString)) // not valid
+    {
+      throw (new NumberFormatException("Not a valid memory string"));
+    }
+    char suffix = Character
+            .toLowerCase(memString.charAt(memString.length() - 1));
+    if ('0' <= suffix && suffix <= '9') // no suffix
+    {
+      return Long.valueOf(memString);
+    }
+    if (memorySuffixes.indexOf(suffix) == -1) // suffix is unknown
+    {
+      return -1;
+    }
+
+    long multiplier = (long) Math.pow(2,
+            memorySuffixes.indexOf(suffix) * 10); // note order of suffixes in
+                                                  // memorySuffixes important
+                                                  // here!
+    // parse the arg. NumberFormatExceptions passed on to calling method
+    long mem = Long
+            .parseLong(memString.substring(0, memString.length() - 1));
+    if (mem == 0)
+    {
+      return 0;
+    }
+
+    // apply multiplier only if result is not too big (i.e. bigger than a long)
+    if (Long.MAX_VALUE / mem > multiplier)
+    {
+      return multiplier * mem;
+    }
+    else
+    {
+      // number too big for a Long. Limit to Long.MAX_VALUE
+      System.out.println("Memory parsing of '" + memString
+              + "' produces number too big.  Limiting to Long.MAX_VALUE="
+              + Long.MAX_VALUE);
+      return Long.MAX_VALUE;
+    }
+  }
+
+  public static String memoryLongToString(long mem)
+  {
+    return memoryLongToString(mem, "%.3f");
+  }
+
+  public static String memoryLongToString(long mem, String format)
+  {
+    int exponent = 0;
+    float num = mem;
+    char suffix = 'b';
+
+    for (int i = 0; i < memorySuffixes.length(); i++)
+    {
+      char s = Character.toUpperCase(memorySuffixes.charAt(i));
+      if (mem < (long) Math.pow(2, exponent + 10)
+              || i == memorySuffixes.length() - 1) // last suffix
+      {
+        suffix = s;
+        num = (float) (mem / Math.pow(2, exponent));
+        break;
+      }
+      exponent += 10;
+    }
+
+    return String.format(format, num) + suffix;
+  }
+
+  private static String ADJUSTMENT_MESSAGE = null;
+
+  private static void setAdjustmentMessage(String reason, boolean quiet)
+  {
+    ADJUSTMENT_MESSAGE = reason;
+    if (!quiet)
+    {
+      System.out.println(reason);
+    }
+  }
+
+  public static void clearAdjustmentMessage()
+  {
+    ADJUSTMENT_MESSAGE = null;
+  }
+
+  public static String getAdjustmentMessage()
+  {
+    return ADJUSTMENT_MESSAGE;
+  }
+
+}
index 2f33e43..b376c80 100644 (file)
@@ -118,15 +118,44 @@ public class AlignedCodonFrame
      */
     public boolean covers(SequenceI seq)
     {
-      List<int[]> mappedRanges = null;
+      return covers(seq,false,false);
+    }
+    /**
+     * 
+     * @param seq
+     * @param localCover - when true - compare extent of seq's dataset sequence rather than the local extent
+     * @param either - when true coverage is required for either seq or the mapped sequence 
+     * @return true if mapping covers full length of given sequence (or the other if either==true)
+     */
+    public boolean covers(SequenceI seq, boolean localCover,boolean either)
+    {
+      List<int[]> mappedRanges = null,otherRanges=null;
       MapList mapList = mapping.getMap();
+      int mstart=seq.getStart(),mend=seq.getEnd(),ostart,oend;
+              ;
       if (fromSeq == seq || fromSeq == seq.getDatasetSequence())
       {
+        if (localCover && fromSeq !=seq)
+        {
+          mstart=fromSeq.getStart();
+          mend=fromSeq.getEnd();
+        }
         mappedRanges = mapList.getFromRanges();
+        otherRanges=mapList.getToRanges();
+        ostart=mapping.to.getStart();
+        oend=mapping.to.getEnd();
       }
       else if (mapping.to == seq || mapping.to == seq.getDatasetSequence())
       {
+        if (localCover && mapping.to !=seq)
+        {
+          mstart=mapping.to.getStart();
+          mend=mapping.to.getEnd();
+        }
         mappedRanges = mapList.getToRanges();
+        otherRanges=mapList.getFromRanges();
+        ostart=fromSeq.getStart();
+        oend=fromSeq.getEnd();
       }
       else
       {
@@ -138,29 +167,50 @@ public class AlignedCodonFrame
        * (necessary for circular CDS - example EMBL:J03321:AAA91567)
        * and mapped length covers (at least) sequence length
        */
-      int length = 0;
+      int length = countRange(mappedRanges,mstart,mend);
+
+      if (length != -1)
+      {
+        // add 3 to mapped length to allow for a mapped stop codon
+        if (length + 3 >= (mend - mstart + 1))
+        {
+          return true;
+        }
+      }
+      if (either)
+      {
+        // also check coverage of the other range
+        length = countRange(otherRanges, ostart, oend);
+        if (length != -1)
+        {
+          if (length + 1 >= (oend - ostart + 1))
+          {
+            return true;
+          }
+        }
+      }
+      return false;
+    }
+    private int countRange(List<int[]> mappedRanges,int mstart,int mend)
+    {
+      int length=0;
       for (int[] range : mappedRanges)
       {
         int from = Math.min(range[0], range[1]);
         int to = Math.max(range[0], range[1]);
-        if (from < seq.getStart() || to > seq.getEnd())
+        if (from < mstart || to > mend)
         {
-          return false;
+          return -1;
         }
         length += (to - from + 1);
       }
-      // add 1 to mapped length to allow for a mapped stop codon
-      if (length + 1 < (seq.getEnd() - seq.getStart() + 1))
-      {
-        return false;
-      }
-      return true;
+      return length;
     }
 
     /**
      * Adds any regions mapped to or from position {@code pos} in sequence
      * {@code seq} to the given search results
-     * 
+     * Note: recommend first using the .covers(,true,true) to ensure mapping covers both sequences
      * @param seq
      * @param pos
      * @param sr
@@ -402,7 +452,9 @@ public class AlignedCodonFrame
     }
     for (SequenceToSequenceMapping ssm : mappings)
     {
-      ssm.markMappedRegion(ds, index, results);
+      if (ssm.covers(seq,true,true)) {
+        ssm.markMappedRegion(ds, index, results);
+      }
     }
   }
 
index f145d93..ca6db1b 100644 (file)
@@ -296,8 +296,8 @@ public class MappedFeatures
   public int[] getMappedPositions(int begin, int end)
   {
     MapList map = mapping.getMap();
-    return mapping.to == featureSequence ? map.locateInFrom(begin, end)
-            : map.locateInTo(begin, end);
+    return mapping.to == featureSequence ? map.getOverlapsInFrom(begin, end)
+            : map.getOverlapsInTo(begin, end);
   }
 
   /**
index 6eeba2f..bbf1b45 100755 (executable)
@@ -612,10 +612,9 @@ public class SequenceFeature implements FeatureLocationI
     String consequence = "";
     if (mf != null)
     {
-      int[] beginRange = mf.getMappedPositions(begin, begin);
-      int[] endRange = mf.getMappedPositions(end, end);
-      int from = beginRange[0];
-      int to = endRange[endRange.length - 1];
+      int[] localRange = mf.getMappedPositions(begin, end);
+      int from = localRange[0];
+      int to = localRange[localRange.length - 1];
       String s = mf.isFromCds() ? "Peptide Location" : "Coding location";
       sb.append(String.format(ROW_DATA, s, seqName, from == to ? from
               : from + (isContactFeature() ? ":" : "-") + to));
index 9b56d6b..3dca1b7 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.ext.ensembl;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.GeneLociI;
 import jalview.datamodel.GeneLocus;
@@ -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());
+      Console.error("Error looking up gene loci: " + e.getMessage());
       e.printStackTrace();
     }
     return null;
index fd8800f..e4fa53d 100644 (file)
@@ -33,7 +33,7 @@ import org.json.simple.parser.ParseException;
 
 import jalview.analysis.AlignmentUtils;
 import jalview.analysis.Dna;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
@@ -312,7 +312,7 @@ public abstract class EnsemblSeqProxy extends EnsemblRestClient
 
               if (upx.size() > 1)
               {
-                Cache.log.warn(
+                Console.warn(
                         "Implementation issue - multiple uniprot acc on product sequence.");
               }
             }
index 16ff41b..e91164a 100644 (file)
@@ -20,8 +20,6 @@
  */
 package jalview.ext.htsjdk;
 
-import jalview.bin.Cache;
-
 import java.io.Closeable;
 import java.io.File;
 import java.io.IOException;
@@ -30,6 +28,7 @@ import htsjdk.samtools.util.CloseableIterator;
 import htsjdk.variant.variantcontext.VariantContext;
 import htsjdk.variant.vcf.VCFFileReader;
 import htsjdk.variant.vcf.VCFHeader;
+import jalview.bin.Console;
 
 /**
  * A thin wrapper for htsjdk classes to read either plain, or compressed, or
@@ -85,7 +84,7 @@ public class VCFReader implements Closeable, Iterable<VariantContext>
     }
     else
     {
-      Cache.log.error("File not found: " + filePath);
+      Console.error("File not found: " + filePath);
     }
   }
 
index 903d9b7..895db9a 100644 (file)
@@ -45,7 +45,7 @@ import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureRenderer;
 import jalview.api.FeatureSettingsModelI;
 import jalview.api.SequenceRenderer;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AppJmol;
@@ -122,9 +122,9 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
 
   private String jmolScript(String script)
   {
-    Cache.log.debug(">>Jmol>> " + script);
+    Console.debug(">>Jmol>> " + script);
     String s = jmolViewer.evalStringQuiet(script); // scriptWait(script); BH
-    Cache.log.debug("<<Jmol<< " + s);
+    Console.debug("<<Jmol<< " + s);
 
     return s;
   }
index 5f22526..db71269 100644 (file)
@@ -14,6 +14,7 @@ import java.util.ArrayList;
 import java.util.List;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.Preferences;
 import jalview.structure.StructureCommand;
 import jalview.structure.StructureCommandI;
@@ -140,7 +141,7 @@ public class PymolManager
       int rc = conn.getResponseCode();
       if (rc != HttpURLConnection.HTTP_OK)
       {
-        Cache.log.error(
+        Console.error(
                 String.format("Error status from %s: %d", rpcUrl, rc));
         return result;
       }
@@ -158,7 +159,7 @@ public class PymolManager
     } catch (SocketException e)
     {
       // thrown when 'quit' command is sent to PyMol
-      Cache.log.warn(String.format("Request to %s returned %s", rpcUrl,
+      Console.warn(String.format("Request to %s returned %s", rpcUrl,
               e.toString()));
     } catch (Exception e)
     {
@@ -169,12 +170,12 @@ public class PymolManager
       {
         out.close();
       }
-      if (Cache.log.isTraceEnabled())
+      if (Console.isTraceEnabled())
       {
-        Cache.log.trace("Sent: " + command.toString());
+        Console.trace("Sent: " + command.toString());
         if (result != null)
         {
-          Cache.log.trace("Received: " + result);
+          Console.trace("Received: " + result);
         }
       }
     }
@@ -251,12 +252,12 @@ public class PymolManager
       this.pymolXmlRpcPort = getPortNumber();
       if (pymolXmlRpcPort > 0)
       {
-        Cache.log.info("PyMOL XMLRPC started on port " + pymolXmlRpcPort);
+        Console.info("PyMOL XMLRPC started on port " + pymolXmlRpcPort);
       }
       else
       {
         error += "Failed to read PyMOL XMLRPC port number";
-        Cache.log.error(error);
+        Console.error(error);
         pymolProcess.destroy();
         pymolProcess = null;
       }
@@ -300,7 +301,7 @@ public class PymolManager
       }
     } catch (Exception e)
     {
-      Cache.log.error("Failed to get REST port number from " + responses
+      Console.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 +316,10 @@ public class PymolManager
     }
     if (port == 0)
     {
-      Cache.log.error("Failed to start PyMOL with XMLRPC, response was: "
+      Console.error("Failed to start PyMOL with XMLRPC, response was: "
               + responses);
     }
-    Cache.log.error("PyMOL started with XMLRPC on port " + port);
+    Console.error("PyMOL started with XMLRPC on port " + port);
     return port;
   }
 
index 7169fa2..c78a82b 100644 (file)
@@ -36,7 +36,7 @@ import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
 import jalview.api.AlignmentViewPanel;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SearchResultMatchI;
 import jalview.datamodel.SearchResultsI;
@@ -337,16 +337,16 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
     if (getResponse)
     {
       reply = lastReply;
-      if (Cache.log.isDebugEnabled()) {
-        Cache.log.debug(
+      if (Console.isDebugEnabled()) {
+        Console.debug(
               "Response from command ('" + cmd + "') was:\n" + lastReply); 
       }
     }
     else
     {
-      if (Cache.log.isDebugEnabled())
+      if (Console.isDebugEnabled())
       {
-        Cache.log.debug("Command executed: " + cmd);
+        Console.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);
+        Console.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);
+        Console.error("Problem parsing atomspec " + atomSpec);
         continue;
       }
 
index 138aa58..38d98d0 100644 (file)
@@ -42,7 +42,7 @@ import org.biojava.nbio.ontology.Triple;
 import org.biojava.nbio.ontology.io.OboParser;
 import org.biojava.nbio.ontology.utils.Annotation;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.io.gff.SequenceOntologyI;
 
 /**
@@ -115,7 +115,7 @@ public class SequenceOntology implements SequenceOntologyI
         }
       }
       long elapsed = System.currentTimeMillis() - now;
-      Cache.log.info("Loaded Sequence Ontology from " + zipFile + " ("
+      Console.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()
+              Console.debug("Ignoring " + term.getName()
                       + " as obsolete and duplicated by "
                       + replaced.getName());
               term = replaced;
             }
             else if (!newTermIsObsolete && oldTermIsObsolete)
             {
-              Cache.log.debug("Ignoring " + replaced.getName()
+              Console.debug("Ignoring " + replaced.getName()
                       + " as obsolete and duplicated by " + term.getName());
             }
             else
             {
-              Cache.log.debug("Warning: " + term.getName()
+              Console.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");
+        Console.error("SO term " + term + " invalid");
         termsNotFound.add(term);
       }
     }
index ebf9ec5..da43bea 100644 (file)
@@ -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()));
       }
     });
index 6b855fc..5ee7aaa 100644 (file)
@@ -8,6 +8,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 
+import jalview.bin.Console;
 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);
+        Console.debug("Exception accessing urls", mfe);
         continue;
       }
       int colCounter = 0;
index 7fa6aa5..99f1a71 100644 (file)
@@ -15,7 +15,7 @@ import javax.swing.SwingUtilities;
 import org.json.JSONArray;
 import org.json.JSONObject;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.fts.api.FTSDataColumnI;
 import jalview.fts.api.FTSRestClientI;
@@ -214,7 +214,7 @@ public class TDBeaconsFTSPanel extends GFTSPanel
             }
           } catch (Exception x)
           {
-            Cache.log.warn(
+            Console.warn(
                     "Couldn't retrieve 3d-beacons model for uniprot id"
                             + searchTerm + " : " + tdbURL,
                     x);
index fb9b707..4d3a3f3 100644 (file)
@@ -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);
index 8deff01..07baa2e 100644 (file)
@@ -93,6 +93,7 @@ import jalview.api.SplitContainerI;
 import jalview.api.ViewStyleI;
 import jalview.api.analysis.SimilarityParamsI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.bin.Jalview;
 import jalview.commands.CommandI;
 import jalview.commands.EditCommand;
@@ -368,7 +369,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 +412,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 +1015,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 +1217,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       }
       else
       {
-        Cache.log.error(MessageManager
+        Console.error(MessageManager
                 .formatMessage("label.couldnt_save_file", new Object[]
                 { lastFilenameSaved }));
       }
@@ -1299,7 +1300,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           BackupFiles backupfiles = null;
           if (doBackup)
           {
-            Cache.log.trace(
+            Console.trace(
                     "ALIGNFRAME making backupfiles object for " + file);
             backupfiles = new BackupFiles(file);
           }
@@ -1307,19 +1308,19 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           {
             String tempFilePath = doBackup ? backupfiles.getTempFilePath()
                     : file;
-            Cache.log.trace("ALIGNFRAME setting PrintWriter");
+            Console.trace("ALIGNFRAME setting PrintWriter");
             PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
 
             if (backupfiles != null)
             {
-              Cache.log.trace("ALIGNFRAME about to write to temp file "
+              Console.trace("ALIGNFRAME about to write to temp file "
                       + backupfiles.getTempFilePath());
             }
 
             out.print(output);
-            Cache.log.trace("ALIGNFRAME about to close file");
+            Console.trace("ALIGNFRAME about to close file");
             out.close();
-            Cache.log.trace("ALIGNFRAME closed file");
+            Console.trace("ALIGNFRAME closed file");
             AlignFrame.this.setTitle(file);
             statusBar.setText(MessageManager.formatMessage(
                     "label.successfully_saved_to_file_in_format",
@@ -1329,29 +1330,29 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           } catch (IOException e)
           {
             lastSaveSuccessful = false;
-            Cache.log.error(
+            Console.error(
                     "ALIGNFRAME Something happened writing the temp file");
-            Cache.log.error(e.getMessage());
-            Cache.log.debug(Cache.getStackTraceString(e));
+            Console.error(e.getMessage());
+            Console.debug(Cache.getStackTraceString(e));
           } catch (Exception ex)
           {
             lastSaveSuccessful = false;
-            Cache.log.error(
+            Console.error(
                     "ALIGNFRAME Something unexpected happened writing the temp file");
-            Cache.log.error(ex.getMessage());
-            Cache.log.debug(Cache.getStackTraceString(ex));
+            Console.error(ex.getMessage());
+            Console.debug(Cache.getStackTraceString(ex));
           }
 
           if (doBackup)
           {
             backupfiles.setWriteSuccess(lastSaveSuccessful);
-            Cache.log.debug("ALIGNFRAME writing temp file was "
+            Console.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(
+            Console.trace(
                     "ALIGNFRAME about to rollBackupsAndRenameTempFile");
             lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
-            Cache.log.debug(
+            Console.debug(
                     "ALIGNFRAME performed rollBackupsAndRenameTempFile "
                             + (lastSaveSuccessful ? "" : "un")
                             + "successfully");
@@ -1534,7 +1535,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 +1547,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 +1734,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     {
       if (originalSource != viewport)
       {
-        Cache.log.warn(
+        Console.warn(
                 "Implementation worry: mismatch of viewport origin for undo");
       }
       originalSource.updateHiddenColumns();
@@ -1773,7 +1774,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
       if (originalSource != viewport)
       {
-        Cache.log.warn(
+        Console.warn(
                 "Implementation worry: mismatch of viewport origin for redo");
       }
       originalSource.updateHiddenColumns();
@@ -4069,7 +4070,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 +4334,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                 }
               } catch (Exception e)
               {
-                Cache.log.debug(
+                Console.debug(
                         "Exception during web service menu building process.",
                         e);
               }
@@ -4430,7 +4431,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       showProducts.setEnabled(showp);
     } catch (Exception e)
     {
-      Cache.log.warn(
+      Console.warn(
               "canShowProducts threw an exception - please report to help@jalview.org",
               e);
       return false;
@@ -4471,7 +4472,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       al = dna.translateCdna(codeTable);
     } catch (Exception ex)
     {
-      jalview.bin.Cache.log.error(
+      Console.error(
               "Exception during translation. Please report this !", ex);
       final String msg = MessageManager.getString(
               "label.error_when_translating_sequences_submit_bug_report");
@@ -4834,7 +4835,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           }
         } catch (Exception x)
         {
-          Cache.log.debug(
+          Console.debug(
                   "Exception when processing data source as T-COFFEE score file",
                   x);
           tcf = null;
index 55abea6..092d7e7 100644 (file)
@@ -29,6 +29,7 @@ import jalview.api.FeatureSettingsModelI;
 import jalview.api.FeaturesDisplayedI;
 import jalview.api.ViewStyleI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.commands.CommandI;
 import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.Alignment;
@@ -123,14 +124,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(
+      Console.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);
+      Console.debug("Setting viewport's view id : " + viewId);
     }
     init();
 
@@ -185,14 +186,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(
+      Console.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);
+      Console.debug("Setting viewport's view id : " + viewId);
     }
 
     if (hiddenColumns != null)
@@ -594,7 +595,7 @@ public class AlignViewport extends AlignmentViewport
     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
     if (needsUpdate)
     {
-      Cache.log.debug("trigger update for " + calcId);
+      Console.debug("trigger update for " + calcId);
     }
   }
 
@@ -824,7 +825,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)
     {
     }
index 35b19c1..5366913 100644 (file)
@@ -24,6 +24,7 @@ import jalview.analysis.AnnotationSorter;
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.bin.Jalview;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.HiddenColumns;
@@ -806,7 +807,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(
+          Console.warn(
                   "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
 
           // scroll to start of panel
@@ -1464,9 +1465,9 @@ public class AlignmentPanel extends GAlignmentPanel implements
     }
     else
     {
-      if (Cache.log.isDebugEnabled())
+      if (Console.isDebugEnabled())
       {
-        Cache.log.warn("Closing alignment panel which is already closed.");
+        Console.warn("Closing alignment panel which is already closed.");
       }
     }
   }
index 217d2b1..16d0dd7 100644 (file)
@@ -38,7 +38,7 @@ import javax.swing.event.InternalFrameAdapter;
 import javax.swing.event.InternalFrameEvent;
 
 import jalview.api.AlignmentViewPanel;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.datamodel.StructureViewerModel;
@@ -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);
+        Console.debug("File locations are " + filesString);
       } catch (Exception ex)
       {
-        Cache.log.error("Couldn't open Jmol viewer!", ex);
+        Console.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);
+        Console.debug("File locations are " + filesString);
         return;
       } catch (Exception ex)
       {
-        Cache.log.error("Couldn't add files to Jmol viewer!", ex);
+        Console.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.");
+        Console.debug("Waiting around for jmb notify.");
         waitTotal += waitFor;
 
         // Thread.sleep() throws an exception in JS
index 6b06e56..34d930d 100644 (file)
@@ -33,7 +33,7 @@ import org.openscience.jmol.app.jmolpanel.console.AppConsole;
 
 import jalview.api.AlignmentViewPanel;
 import jalview.api.structures.JalviewStructureDisplayI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
@@ -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);
+      Console.error("Failed to launch Jmol-associated url " + url, e);
       // TODO: 2.6 : warn user if browser was not configured.
     }
   }
index 8ba3dce..3dc51ce 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.gui;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.util.MessageManager;
 
 import java.awt.BorderLayout;
@@ -199,7 +200,7 @@ public class BlogReader extends JPanel
       {
         if (parent != null)
         {
-          Cache.log.debug("News window closed.");
+          Console.debug("News window closed.");
           jd = null;
           parent.showNews(false);
         }
@@ -247,15 +248,15 @@ public class BlogReader extends JPanel
 
   public BlogReader(Desktop desktop)
   {
-    Cache.log.debug("Constructing news reader.");
+    Console.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 +278,10 @@ public class BlogReader extends JPanel
     if (setvisible)
     {
 
-      Cache.log.debug("Will show jalview news automatically");
+      Console.debug("Will show jalview news automatically");
       showNews();
     }
-    Cache.log.debug("Completed construction of reader.");
+    Console.debug("Completed construction of reader.");
 
   }
 
@@ -340,7 +341,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.");
+          Console.debug("Displaying news.");
           jd.waitForInput();
         }
       }
@@ -367,7 +368,7 @@ public class BlogReader extends JPanel
     }
     if (chan != null && chan.getItems() != null)
     {
-      Cache.log.debug("Scanning news items: newsnew=" + newsnew
+      Console.debug("Scanning news items: newsnew=" + newsnew
               + " and lastDate is " + lastDate);
       for (Item i : (List<Item>) chan.getItems())
       {
@@ -426,7 +427,7 @@ public class BlogReader extends JPanel
       {
         String formatted = Cache
                 .setDateProperty("JALVIEW_NEWS_RSS_LASTMODIFIED", lastDate);
-        Cache.log.debug("Saved last read date as " + formatted);
+        Console.debug("Saved last read date as " + formatted);
       }
     }
   }
@@ -759,8 +760,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);
+    Console.initLogger();
     // test will advance read date each time
     Calendar today = Calendar.getInstance(),
             lastread = Calendar.getInstance();
@@ -773,16 +774,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.");
+        Console.debug("There is news to read.");
       }
       else
       {
-        Cache.log.debug("There is no new news.");
+        Console.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.");
+      Console.debug("Waiting for closure.");
       do
       {
         try
@@ -795,11 +796,11 @@ public class BlogReader extends JPanel
 
       if (me.isNewsNew())
       {
-        Cache.log.debug("Still new news after reader displayed.");
+        Console.debug("Still new news after reader displayed.");
       }
       if (lastread.getTime().before(me.lastDate))
       {
-        Cache.log.debug("The news was read.");
+        Console.debug("The news was read.");
         lastread.setTime(me.lastDate);
       }
       else
index 8dd0174..9d98585 100644 (file)
@@ -38,7 +38,7 @@ import javax.swing.event.InternalFrameEvent;
 
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureRenderer;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.datamodel.StructureViewerModel;
@@ -441,7 +441,7 @@ public class ChimeraViewFrame extends StructureViewerBase
           initChimera();
         } catch (Exception ex)
         {
-          Cache.log.error("Couldn't open Chimera viewer!", ex);
+          Console.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(
+            Console.error(
                     "Couldn't open " + pe.getFile() + " in Chimera viewer!",
                     ex);
           } finally
           {
-            Cache.log.debug("File locations are " + files);
+            Console.debug("File locations are " + files);
           }
         }
       }
index 050523e..d9d729a 100644 (file)
@@ -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,15 @@ import javax.swing.JLabel;
 import javax.swing.JPanel;
 import javax.swing.JScrollPane;
 import javax.swing.JTextArea;
+import javax.swing.border.Border;
+import javax.swing.text.DefaultCaret;
 
-import org.apache.log4j.Level;
-import org.apache.log4j.SimpleLayout;
-
-import jalview.bin.Cache;
+import jalview.log.JLoggerI.LogLevel;
+import jalview.log.JLoggerLog4j;
+import jalview.log.JalviewAppender;
 import jalview.util.ChannelProperties;
 import jalview.util.MessageManager;
+import jalview.util.Platform;
 
 /**
  * Simple Jalview Java Console. Version 1 - allows viewing of console output
@@ -101,9 +104,9 @@ public class Console extends WindowAdapter
 
   private int MIN_HEIGHT = 250;
 
-  private JComboBox<Level> logLevelCombo = new JComboBox<Level>();
+  private JComboBox<LogLevel> logLevelCombo = new JComboBox<LogLevel>();
 
-  protected Level startingLogLevel = Level.INFO;
+  protected LogLevel startingLogLevel = LogLevel.INFO;
 
   public Console()
   {
@@ -132,6 +135,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,25 +201,26 @@ 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
-            : Cache.log.getLevel();
+    startingLogLevel = jalview.bin.Console.log == null ? LogLevel.INFO
+            : jalview.bin.Console.log.getLevel();
     setChosenLogLevelCombo();
     logLevelCombo.addActionListener(new ActionListener()
     {
       public void actionPerformed(ActionEvent e)
       {
-        if (Cache.log != null)
+        if (jalview.bin.Console.log != null)
         {
-          Cache.log.setLevel((Level) logLevelCombo.getSelectedItem());
+          jalview.bin.Console.log.setLevel((LogLevel) logLevelCombo.getSelectedItem());
         }
       }
 
@@ -194,8 +228,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());
 
@@ -266,20 +299,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.isGreaterOrEqual(setLogLevel))
+          LogLevel l = (LogLevel) logLevelCombo.getItemAt(i);
+          if (l.compareTo(setLogLevel) >= 0)
           {
             logLevelCombo.insertItemAt(setLogLevel, i);
             added = true;
@@ -295,7 +328,7 @@ public class Console extends WindowAdapter
       }
       else
       {
-        logLevelCombo.setSelectedItem(Level.INFO);
+        logLevelCombo.setSelectedItem(LogLevel.INFO);
       }
     }
   }
@@ -471,10 +504,17 @@ public class Console extends WindowAdapter
     frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
     // desktop.add(frame);
     initConsole(false);
-    JalviewAppender jappender = new JalviewAppender();
-    jappender.setLayout(new SimpleLayout());
-    JalviewAppender.setTextArea(textArea);
-    org.apache.log4j.Logger.getRootLogger().addAppender(jappender);
+    LogLevel level = (LogLevel) logLevelCombo.getSelectedItem();
+    if (!Platform.isJS())
+    {
+      JalviewAppender jappender = new JalviewAppender(level);
+      JalviewAppender.setTextArea(textArea);
+      jappender.start();
+      if (jalview.bin.Console.log != null && jalview.bin.Console.log instanceof JLoggerLog4j)
+      {
+        JLoggerLog4j.addAppender(jalview.bin.Console.log, jappender);
+      }
+    }
   }
 
   public synchronized void stopConsole()
@@ -815,9 +855,9 @@ public class Console extends WindowAdapter
     else
     {
       // reset log level to what it was before
-      if (Cache.log != null)
+      if (jalview.bin.Console.log != null)
       {
-        Cache.log.setLevel(startingLogLevel);
+        jalview.bin.Console.log.setLevel(startingLogLevel);
       }
 
       unredirectStreams();
index 2ada4d2..b04661e 100644 (file)
@@ -25,6 +25,7 @@ import jalview.analysis.CrossRef;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureSettingsModelI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
@@ -229,7 +230,7 @@ public class CrossRefAction implements Runnable
       new OOMWarning("whilst fetching crossreferences", e);
     } catch (Throwable e)
     {
-      Cache.log.error("Error when finding crossreferences", e);
+      Console.error("Error when finding crossreferences", e);
     } finally
     {
       alignFrame.setProgressBar(MessageManager.formatMessage(
index fc19695..6e0032f 100644 (file)
@@ -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());
index 3f64ff1..5e36500 100644 (file)
@@ -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)
         {
         }
index 0f80dd5..ad36492 100644 (file)
@@ -382,11 +382,11 @@ public class Desktop extends jalview.jbgui.GDesktop
           awtAppClassNameField.setAccessible(true);
           awtAppClassNameField.set(xToolkit, title);
         } else {
-          Cache.log.debug("XToolkit: awtAppClassName not found");
+          jalview.bin.Console.debug("XToolkit: awtAppClassName not found");
         }
       } catch (Exception e) {
-        Cache.debug("Error setting awtAppClassName");
-        Cache.trace(Cache.getStackTraceString(e));
+        jalview.bin.Console.debug("Error setting awtAppClassName");
+        jalview.bin.Console.trace(Cache.getStackTraceString(e));
       }
     }
 
@@ -401,8 +401,8 @@ public class Desktop extends jalview.jbgui.GDesktop
       System.out.println("Cannot set APQHandlers");
       // e.printStackTrace();
     } catch (Throwable t) {
-      Cache.warn("Error setting APQHandlers: " + t.toString());
-      Cache.trace(Cache.getStackTraceString(t));
+      jalview.bin.Console.warn("Error setting APQHandlers: " + t.toString());
+      jalview.bin.Console.trace(Cache.getStackTraceString(t));
     }
     setIconImages(ChannelProperties.getIconList());
 
@@ -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.");
+          jalview.bin.Console.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.");
+          jalview.bin.Console.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());
+          jalview.bin.Console.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.");
+        jalview.bin.Console.debug("Starting news thread.");
         jvnews = new BlogReader(me);
         showNews.setVisible(true);
-        Cache.log.debug("Completed news thread.");
+        jalview.bin.Console.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");
+          jalview.bin.Console.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());
+            jalview.bin.Console.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.");
+    jalview.bin.Console.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.");
+          jalview.bin.Console.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.");
+          jalview.bin.Console.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
+        jalview.bin.Console.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(
+      jalview.bin.Console.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
+    jalview.bin.Console.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...");
+    jalview.bin.Console.debug("Collecting garbage...");
     System.gc();
-    Cache.log.debug("Finished garbage collection.");
+    jalview.bin.Console.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);
+            jalview.bin.Console.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);
+              jalview.bin.Console.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);
+      jalview.bin.Console.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);
+          jalview.bin.Console.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.");
-          }
+          jalview.bin.Console.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);
+          jalview.bin.Console.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());
+        jalview.bin.Console.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);
+      jalview.bin.Console.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));
+          jalview.bin.Console.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);
+        jalview.bin.Console.debug("URL drop handler failed.", ex);
       }
     }
     if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
       // Works on Windows and MacOSX
-      Cache.log.debug("Drop handled as javaFileListFlavor");
+      jalview.bin.Console.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");
+        jalview.bin.Console.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");
+        jalview.bin.Console.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));
+        jalview.bin.Console.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()));
+          jalview.bin.Console.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 (jalview.bin.Console.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:");
+            jalview.bin.Console.debug("Couldn't resolve drop data. Here are the supported flavors:");
             for (DataFlavor fl : t.getTransferDataFlavors()) {
-              Cache.log.debug("Supported transfer dataflavor: " + fl.toString());
+              jalview.bin.Console.debug("Supported transfer dataflavor: " + fl.toString());
               Object df = t.getTransferData(fl);
               if (df != null) {
-                Cache.log.debug("Retrieves: " + df);
+                jalview.bin.Console.debug("Retrieves: " + df);
               } else {
-                Cache.log.debug("Retrieved nothing");
+                jalview.bin.Console.debug("Retrieved nothing");
               }
             }
           } else {
-            Cache.log.debug("Couldn't resolve dataflavor for drop: " + t.toString());
+            jalview.bin.Console.debug("Couldn't resolve dataflavor for drop: " + t.toString());
           }
         }
       }
     }
     if (Platform.isWindowsAndNotJS()) {
-      Cache.log.debug("Scanning dropped content for Windows Link Files");
+      jalview.bin.Console.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);
+            jalview.bin.Console.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));
+            jalview.bin.Console.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);
+            jalview.bin.Console.error("Couldn't parse " + files.get(f) + " as a link file.", ex);
           }
         }
       }
@@ -2782,14 +2778,14 @@ public class Desktop extends jalview.jbgui.GDesktop
         AffineTransform t = gg.getTransform();
         double scaleX = t.getScaleX();
         double scaleY = t.getScaleY();
-        Cache.debug(debugScaleMessage + scaleX + " (X)");
-        Cache.debug(debugScaleMessage + scaleY + " (Y)");
+        jalview.bin.Console.debug(debugScaleMessage + scaleX + " (X)");
+        jalview.bin.Console.debug(debugScaleMessage + scaleY + " (Y)");
         debugScaleMessageDone = true;
       } else {
-        Cache.debug("Desktop graphics null");
+        jalview.bin.Console.debug("Desktop graphics null");
       }
     } catch (Exception e) {
-      Cache.debug(Cache.getStackTraceString(e));
+      jalview.bin.Console.debug(Cache.getStackTraceString(e));
     }
   }
 }
index 572ada6..ac04a1f 100644 (file)
@@ -498,81 +498,6 @@ public class FeatureSettings extends JPanel
     JPopupMenu men = new JPopupMenu(MessageManager
             .formatMessage("label.settings_for_param", new String[]
             { type }));
-    final FeatureColourI featureColour = (FeatureColourI) typeCol;
-
-    /*
-     * menu option to select (or deselect) variable colour
-     */
-    final JCheckBoxMenuItem variableColourCB = new JCheckBoxMenuItem(
-            MessageManager.getString("label.variable_colour"));
-    variableColourCB.setSelected(!featureColour.isSimpleColour());
-    men.add(variableColourCB);
-
-    /*
-     * checkbox action listener doubles up as listener to OK
-     * from the variable colour / filters dialog
-     */
-    variableColourCB.addActionListener(new ActionListener()
-    {
-      @Override
-      public void actionPerformed(ActionEvent e)
-      {
-        if (e.getSource() == variableColourCB)
-        {
-                                       // BH 2018 for JavaScript because this is a checkbox
-                                       men.setVisible(true);
-          men.setVisible(false);
-          if (featureColour.isSimpleColour())
-          {
-            /*
-             * toggle simple colour to variable colour - show dialog
-             */
-            FeatureTypeSettings fc = new FeatureTypeSettings(fr, type);
-            fc.addActionListener(this);
-          }
-          else
-          {
-            /*
-             * toggle variable to simple colour - show colour chooser
-             */
-            String title = MessageManager
-                    .formatMessage("label.select_colour_for", type);
-            ColourChooserListener listener = new ColourChooserListener()
-            {
-              @Override
-              public void colourSelected(Color c)
-              {
-                table.setValueAt(new FeatureColour(c), rowSelected,
-                        COLOUR_COLUMN);
-                table.validate();
-                updateFeatureRenderer(
-                        ((FeatureTableModel) table.getModel()).getData(),
-                        false);
-              }
-            };
-            JalviewColourChooser.showColourChooser(FeatureSettings.this,
-                    title, featureColour.getMaxColour(), listener);
-          }
-        }
-        else
-        {
-          if (e.getSource() instanceof FeatureTypeSettings)
-          {
-            /*
-             * update after OK in feature colour dialog; the updated
-             * colour will have already been set in the FeatureRenderer
-             */
-            FeatureColourI fci = fr.getFeatureColours().get(type);
-            table.setValueAt(fci, rowSelected, COLOUR_COLUMN);
-            // BH 2018 setting a table value does not invalidate it.
-            // System.out.println("FeatureSettings is valied" +
-            // table.validate();
-          }
-        }
-      }
-    });
-
-    men.addSeparator();
 
     JMenuItem scr = new JMenuItem(
             MessageManager.getString("label.sort_by_score"));
index 54eeba7..a2a2700 100644 (file)
@@ -23,7 +23,7 @@ package jalview.gui;
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureColourI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.GraphLine;
 import jalview.datamodel.features.FeatureAttributes;
 import jalview.datamodel.features.FeatureAttributes.Datatype;
@@ -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");
+      Console.error("Problem casting Combo box entry to String");
       attName = attCombo.getSelectedItem().toString();
     }
     Condition cond = (Condition) condCombo.getSelectedItem();
index 02c8fe1..9bdbf61 100644 (file)
@@ -20,6 +20,7 @@
  */
 package jalview.gui;
 
+import jalview.bin.Console;
 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,
+        Console.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();
index 6c76c3e..c0c347a 100644 (file)
@@ -24,7 +24,7 @@ import jalview.analysis.scoremodels.ScoreModels;
 import jalview.api.AlignViewportI;
 import jalview.api.analysis.ScoreModelI;
 import jalview.api.analysis.SimilarityParamsI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
@@ -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(
+      Console.info(
               "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
       return;
     }
index 6cd763b..1c3ab8f 100644 (file)
@@ -56,7 +56,7 @@ import jalview.analysis.AlignmentAnnotationUtils;
 import jalview.analysis.AlignmentUtils;
 import jalview.analysis.Conservation;
 import jalview.api.AlignViewportI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.commands.ChangeCaseCommand;
 import jalview.commands.EditCommand;
 import jalview.commands.EditCommand.Action;
@@ -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);
+        Console.error("Exception for URLLink '" + link + "'", foo);
         continue;
       }
 
       if (!urlLink.isValid())
       {
-        Cache.log.error(urlLink.getInvalidMessage());
+        Console.error(urlLink.getInvalidMessage());
         continue;
       }
 
@@ -839,15 +839,14 @@ public class PopupMenu extends JPopupMenu implements ColourChangeListener
       /*
        * show local rather than linked feature coordinates
        */
-      int[] beginRange = mf.getMappedPositions(start, start);
-      int[] endRange = mf.getMappedPositions(end, end);
-      if (beginRange == null || endRange == null)
+      int[] localRange = mf.getMappedPositions(start, end);
+      if (localRange == null)
       {
         // e.g. variant extending to stop codon so not mappable
         return;
       }
-      start = beginRange[0];
-      end = endRange[endRange.length - 1];
+      start = localRange[0];
+      end = localRange[localRange.length - 1];
     }
     StringBuilder desc = new StringBuilder();
     desc.append(sf.getType()).append(" ").append(String.valueOf(start));
@@ -1166,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);
+        Console.error("Exception for GroupURLLink '" + link + "'", foo);
         continue;
       }
       if (!urlLink.isValid())
       {
-        Cache.log.error(urlLink.getInvalidMessage());
+        Console.error(urlLink.getInvalidMessage());
         continue;
       }
       final String label = urlLink.getLabel();
index d8eee6d..b9f30e3 100755 (executable)
@@ -54,6 +54,8 @@ import javax.swing.table.TableRowSorter;
 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
 import jalview.bin.Cache;
+import jalview.bin.Console;
+import jalview.bin.MemorySetting;
 import jalview.ext.pymol.PymolManager;
 import jalview.gui.Help.HelpId;
 import jalview.gui.StructureViewer.ViewerType;
@@ -431,7 +433,7 @@ public class Preferences extends GPreferences
       }
     } catch (IllegalArgumentException e)
     {
-      Cache.log.error("Unknown structure viewer type: " + viewerType
+      Console.error("Unknown structure viewer type: " + viewerType
               + ", defaulting to Jmol");
       type = ViewerType.JMOL;
     }
@@ -463,7 +465,7 @@ public class Preferences extends GPreferences
           }
         } catch (IllegalArgumentException x)
         {
-          Cache.log.error("Failed to set path - unknown viewer type",x);
+          Console.error("Failed to set path - unknown viewer type",x);
         }
         }
       }
@@ -619,7 +621,7 @@ public class Preferences extends GPreferences
       proxyType.setSelected(customProxy.getModel(), true);
       break;
     default:
-      Cache.log.warn(
+      Console.warn(
               "Incorrect PROXY_TYPE - should be 'none' (clear proxy properties), 'false' (system settings), 'true' (custom settings): "
                       + proxyTypeString);
     }
@@ -683,6 +685,11 @@ public class Preferences extends GPreferences
      * Set Backups tab defaults
      */
     loadLastSavedBackupsOptions();
+
+    /*
+     * Set Startup tab defaults
+     */
+
   }
 
   /**
@@ -995,6 +1002,21 @@ public class Preferences extends GPreferences
     Cache.applicationProperties.setProperty(
             BackupFilesPresetEntry.SAVEDCONFIG, savedBFPE.toString());
 
+    /*
+     * Save Memory Settings
+     */
+    Cache.applicationProperties.setProperty(
+            MemorySetting.CUSTOMISED_SETTINGS,
+            Boolean.toString(customiseMemorySetting.isSelected()));
+    Cache.applicationProperties.setProperty(MemorySetting.MEMORY_JVMMEMPC,
+            Integer.toString(jvmMemoryPercentSlider.getValue()));
+    Cache.applicationProperties.setProperty(MemorySetting.MEMORY_JVMMEMMAX,
+            jvmMemoryMaxTextField.getText());
+
+    /*
+     * save and close Preferences
+     */
+
     Cache.saveProperties();
     Desktop.instance.doConfigureStructurePrefs();
     try
@@ -1168,7 +1190,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");
+      Console.debug("Edit with no row selected in linkUrlTable");
       return;
     }
 
@@ -1220,7 +1242,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");
+      Console.debug("Delete with no row selected in linkUrlTable");
       return;
     }
     else
index cb59452..31db21d 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.gui;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 
 import java.awt.Component;
 
@@ -89,7 +90,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 +127,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.");
+      Console.debug("Got user response.");
     }
-    lastq = jalview.bin.Cache.getProperty(property);
+    lastq = Cache.getProperty(property);
     String extype = "";
     Exception e = null;
     if (lastq == null)
@@ -183,7 +184,7 @@ public class PromptUserConfig implements Runnable
     // report any exceptions
     if (e != null)
     {
-      Cache.log.warn("Unexpected exception when executing the " + extype
+      Console.warn("Unexpected exception when executing the " + extype
               + " runnable for property " + property, e);
     }
   }
@@ -193,9 +194,9 @@ public class PromptUserConfig implements Runnable
    */
   private void raiseDialog()
   {
-    if (jalview.bin.Cache.log.isDebugEnabled())
+    if (Console.isDebugEnabled())
     {
-      jalview.bin.Cache.log.debug("Prompting user for " + dialogTitle
+      Console.debug("Prompting user for " + dialogTitle
               + " for Cache property " + property);
     }
     try
@@ -207,36 +208,36 @@ public class PromptUserConfig implements Runnable
               JvOptionPane.QUESTION_MESSAGE);
 
       // and finish parsing the result
-      jalview.bin.Cache.log.debug("Got response : " + reply);
+      Console.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);
+        Console.debug("User cancelled setting " + property);
         return;
       }
       // verify the property is set for debugging
-      if (jalview.bin.Cache.log.isDebugEnabled())
+      if (Console.isDebugEnabled())
       {
-        jalview.bin.Cache.log.debug("User set property to "
-                + jalview.bin.Cache.getProperty(property));
+        Console.debug("User set property to "
+                + Cache.getProperty(property));
       }
     } catch (Exception e)
     {
-      jalview.bin.Cache.log.warn(
+      Console.warn(
               "Unexpected exception when prompting user for yes/no setting for property "
                       + property,
               e);
index 719ca53..9ef45fb 100644 (file)
@@ -6,7 +6,7 @@ import java.util.List;
 import java.util.Map;
 
 import jalview.api.AlignmentViewPanel;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.ext.pymol.PymolCommands;
@@ -156,7 +156,7 @@ public class PymolBindingModel extends AAStructureBindingModel
     }
     else
     {
-      Cache.log.error("Failed to launch PyMOL!");
+      Console.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);
+      Console.error("Unxpected encoding exception for '"+pdbId+"'",x);
     }
     cmd.addParameter(pdbId);
 
index d7b4236..d426051 100644 (file)
@@ -14,7 +14,7 @@ import javax.swing.event.InternalFrameEvent;
 
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureRenderer;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.datamodel.StructureViewerModel;
@@ -210,7 +210,7 @@ public class PymolViewer extends StructureViewerBase
           initPymol();
         } catch (Exception ex)
         {
-          Cache.log.error("Couldn't open PyMOL viewer!", ex);
+          Console.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(
+            Console.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(
+        Console.error(
                 "An error occurred opening PyMOL session file "
                 + pymolSessionFile);
       }
index 561fb3c..d7cb78a 100755 (executable)
@@ -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))
index 454a730..827c315 100644 (file)
@@ -44,7 +44,7 @@ import javax.swing.Timer;
 import javax.swing.ToolTipManager;
 
 import jalview.api.AlignViewportI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.commands.EditCommand;
 import jalview.commands.EditCommand.Action;
 import jalview.commands.EditCommand.Edit;
@@ -2802,7 +2802,7 @@ public class SeqPanel extends JPanel
     {
       if (av.getAlignment() == null)
       {
-        Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
+        Console.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
                 + " ViewId=" + av.getViewId()
                 + " 's alignment is NULL! returning immediately.");
         return;
index 54aefc4..e596fbf 100755 (executable)
@@ -44,6 +44,7 @@ import javax.swing.SwingConstants;
 
 import jalview.api.FeatureSettingsModelI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.SequenceI;
@@ -811,7 +812,7 @@ public class SequenceFetcher extends JPanel implements Runnable
       }
     } catch (Exception e)
     {
-      Cache.log.info("Error retrieving " + accession + " from "
+      Console.info("Error retrieving " + accession + " from "
               + proxy.getDbName(), e);
     }
     return success;
index ce57373..34fa751 100644 (file)
@@ -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();
     }
   }
index 7b1864b..ad412b0 100644 (file)
@@ -29,6 +29,7 @@ import java.util.Map.Entry;
 
 import jalview.api.structures.JalviewStructureDisplayI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.datamodel.StructureViewerModel;
@@ -180,7 +181,7 @@ public class StructureViewer
     }
     else
     {
-      Cache.log.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
+      Console.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
     }
     return sview;
   }
@@ -328,7 +329,7 @@ public class StructureViewer
     }
     else
     {
-      Cache.log.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
+      Console.error(UNKNOWN_VIEWER_TYPE + getViewerType().toString());
     }
     return sview;
   }
@@ -366,7 +367,7 @@ public class StructureViewer
       viewer = new PymolViewer(viewerData, alignPanel, sessionFile, vid);
       break;
     default:
-      Cache.log.error(UNKNOWN_VIEWER_TYPE + type.toString());
+      Console.error(UNKNOWN_VIEWER_TYPE + type.toString());
     }
     return viewer;
   }
index ae2128b..349871d 100644 (file)
@@ -47,6 +47,7 @@ import javax.swing.event.MenuListener;
 
 import jalview.api.AlignmentViewPanel;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
@@ -814,7 +815,7 @@ public abstract class StructureViewerBase extends GStructureViewer
       {
         sp.append("'" + alignPanel.getViewName() + "' ");
       }
-      Cache.log.info("Couldn't align structures with the " + sp.toString()
+      Console.info("Couldn't align structures with the " + sp.toString()
               + "associated alignment panels.", e);
     }
     return reply;
@@ -1160,7 +1161,7 @@ public abstract class StructureViewerBase extends GStructureViewer
       } else {
           if (processingEntry.hasRetrievalUrl())
           {
-            String safePDBId = java.net.URLEncoder.encode(pdbid,"UTF-8");
+            String safePDBId = java.net.URLEncoder.encode(pdbid,"UTF-8").replace("%","__");
                      
             // retrieve from URL to new local tmpfile
             File tmpFile = File.createTempFile(safePDBId,
index b730df4..db6ba42 100755 (executable)
@@ -30,6 +30,8 @@ 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.bin.Console;
 import jalview.commands.CommandI;
 import jalview.commands.OrderCommand;
 import jalview.datamodel.Alignment;
@@ -408,7 +410,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 +421,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 +460,7 @@ public class TreePanel extends GTreePanel
     AlignmentView originalData = tree.getOriginalData();
     if (originalData == null)
     {
-      jalview.bin.Cache.log.info(
+      Console.info(
               "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
       return;
     }
index ef86756..385eb57 100644 (file)
@@ -20,6 +20,8 @@
  */
 package jalview.gui;
 
+import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.util.MessageManager;
 
 import java.io.BufferedReader;
@@ -42,7 +44,7 @@ public class UserQuestionnaireCheck implements Runnable
   {
     if (url.indexOf("questionnaire.pl") == -1)
     {
-      jalview.bin.Cache.log.error("'" + url
+      Console.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 +58,7 @@ public class UserQuestionnaireCheck implements Runnable
 
   private boolean checkresponse(URL qurl) throws Exception
   {
-    jalview.bin.Cache.log.debug("Checking Response for : " + qurl);
+    Console.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 +103,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 +135,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);
+        Console.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 +149,13 @@ public class UserQuestionnaireCheck implements Runnable
 
         if (reply == JvOptionPane.YES_OPTION)
         {
-          jalview.bin.Cache.log.debug("Opening " + qurl);
+          Console.debug("Opening " + qurl);
           jalview.util.BrowserLauncher.openURL(qurl);
         }
       }
     } catch (Exception e)
     {
-      jalview.bin.Cache.log
-              .warn("When trying to access questionnaire URL " + url, e);
+      Console.warn("When trying to access questionnaire URL " + url, e);
     }
   }
 
index 19ede62..9defed4 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.gui;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.HiddenColumns;
@@ -201,7 +202,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
 
     } catch (Exception e)
     {
-      jalview.bin.Cache.log.error("Couldn't instantiate vamsas client !",
+      Console.error("Couldn't instantiate vamsas client !",
               e);
       return false;
     }
@@ -225,12 +226,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       }
     } catch (Error e)
     {
-      Cache.log.warn(
+      Console.warn(
               "Probable SERIOUS VAMSAS client incompatibility - carrying on regardless",
               e);
     } catch (Exception e)
     {
-      Cache.log.warn(
+      Console.warn(
               "Probable VAMSAS client incompatibility - carrying on regardless",
               e);
     }
@@ -244,7 +245,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 +272,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource
     addStoreDocumentHandler();
     startSession();
     inInitialUpdate = true;
-    Cache.log.debug(
+    Console.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.");
+    Console.debug("... finished update for the first time.");
   }
 
   /**
@@ -306,7 +307,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       }
     } catch (Exception e)
     {
-      Cache.log.warn(
+      Console.warn(
               "Exception whilst refreshing jalview windows after a vamsas document update.",
               e);
     }
@@ -320,10 +321,10 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       @Override
       public void run()
       {
-        Cache.log.info("Jalview updating to the Vamsas Session.");
+        Console.info("Jalview updating to the Vamsas Session.");
 
         dealWithDocumentUpdate(true);
-        Cache.log.info("Jalview finished updating to the Vamsas Session.");
+        Console.info("Jalview finished updating to the Vamsas Session.");
       }
 
     });
@@ -353,7 +354,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.");
+    Console.info("Jalview disconnecting from the Vamsas Session.");
     try
     {
       if (joinedSession)
@@ -361,12 +362,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource
         boolean ourprompt = this.promptUser;
         this.promptUser = promptUser;
         vclient.finalizeClient();
-        Cache.log.info("Jalview has left the session.");
+        Console.info("Jalview has left the session.");
         this.promptUser = ourprompt; // restore default value
       }
       else
       {
-        Cache.log.warn(
+        Console.warn(
                 "JV Client leaving a session that's its not joined yet.");
       }
       joinedSession = false;
@@ -377,13 +378,13 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       vobj2jv = null;
     } catch (Exception e)
     {
-      Cache.log.error("Vamsas Session finalization threw exceptions!", e);
+      Console.error("Vamsas Session finalization threw exceptions!", e);
     }
   }
 
   public void updateJalview(IClientDocument cdoc)
   {
-    Cache.log.debug("Jalview updating from sesion document ..");
+    Console.debug("Jalview updating from sesion document ..");
     ensureJvVamsas();
     VamsasAppDatastore vds = new VamsasAppDatastore(cdoc, vobj2jv, jv2vobj,
             baseProvEntry(), alRedoState);
@@ -392,7 +393,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       vds.updateToJalview();
     } catch (Exception e)
     {
-      Cache.log.error("Failed to update Jalview from vamsas document.", e);
+      Console.error("Failed to update Jalview from vamsas document.", e);
     }
     try
     {
@@ -404,10 +405,10 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       }
     } catch (Exception e)
     {
-      Cache.log.error(
+      Console.error(
               "Exception when updating Jalview settings from Appdata.", e);
     }
-    Cache.log.debug(".. finished updating from sesion document.");
+    Console.debug(".. finished updating from sesion document.");
 
   }
 
@@ -481,7 +482,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
             } catch (Exception e)
             {
               errorsDuringUpdate = true;
-              Cache.log.error("Exception synchronizing " + af.getTitle()
+              Console.error("Exception synchronizing " + af.getTitle()
                       + " "
                       + (af.getViewport().getViewName() == null ? ""
                               : " view " + af.getViewport().getViewName())
@@ -519,7 +520,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       }
     } catch (Exception e)
     {
-      Cache.log.error("Exception synchronizing Views to Document :", e);
+      Console.error("Exception synchronizing Views to Document :", e);
       errorsDuringUpdate = true;
     }
 
@@ -536,7 +537,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       }
     } catch (Exception e)
     {
-      Cache.log.error("Client Appdata Write exception", e);
+      Console.error("Client Appdata Write exception", e);
       errorsDuringAppUpdate = true;
     }
     vds.clearSkipList();
@@ -564,32 +565,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.");
+    Console.debug("Updating jalview from changed vamsas document.");
     disableGui(true);
     try
     {
       long time = System.currentTimeMillis();
       IClientDocument cdoc = vclient.getClientDocument();
-      if (Cache.log.isDebugEnabled())
+      if (Console.isDebugEnabled())
       {
-        Cache.log.debug("Time taken to get ClientDocument = "
+        Console.debug("Time taken to get ClientDocument = "
                 + (System.currentTimeMillis() - time));
         time = System.currentTimeMillis();
       }
       if (fromJalview)
       {
         storedviews += updateVamsasDocument(cdoc);
-        if (Cache.log.isDebugEnabled())
+        if (Console.isDebugEnabled())
         {
-          Cache.log.debug(
+          Console.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 (Console.isDebugEnabled())
         {
-          Cache.log.debug("Time taken to set Document Roots\t\t= "
+          Console.debug("Time taken to set Document Roots\t\t= "
                   + (System.currentTimeMillis() - time));
           time = System.currentTimeMillis();
         }
@@ -597,9 +598,9 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       else
       {
         updateJalview(cdoc);
-        if (Cache.log.isDebugEnabled())
+        if (Console.isDebugEnabled())
         {
-          Cache.log.debug(
+          Console.debug(
                   "Time taken to update Jalview from vamsas document Roots\t= "
                           + (System.currentTimeMillis() - time));
           time = System.currentTimeMillis();
@@ -607,9 +608,9 @@ public class VamsasApplication implements SelectionSource, VamsasSource
 
       }
       vclient.updateDocument(cdoc);
-      if (Cache.log.isDebugEnabled())
+      if (Console.isDebugEnabled())
       {
-        Cache.log.debug("Time taken to update Session Document\t= "
+        Console.debug("Time taken to update Session Document\t= "
                 + (System.currentTimeMillis() - time));
         time = System.currentTimeMillis();
       }
@@ -623,7 +624,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       recover_objectMappingBackup();
       storedviews = 0;
     }
-    Cache.log.debug("Finished updating from document change.");
+    Console.debug("Finished updating from document change.");
     disableGui(false);
     return storedviews;
   }
@@ -636,12 +637,12 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       @Override
       public void propertyChange(PropertyChangeEvent evt)
       {
-        Cache.log.debug("Dealing with document update event.");
+        Console.debug("Dealing with document update event.");
         client.dealWithDocumentUpdate(false);
-        Cache.log.debug("finished dealing with event.");
+        Console.debug("finished dealing with event.");
       }
     });
-    Cache.log.debug("Added Jalview handler for vamsas document updates.");
+    Console.debug("Added Jalview handler for vamsas document updates.");
   }
 
   private void addStoreDocumentHandler()
@@ -656,7 +657,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
               {
                 if (client.promptUser)
                 {
-                  Cache.log.debug(
+                  Console.debug(
                           "Asking user if the vamsas session should be stored.");
                   int reply = JvOptionPane.showInternalConfirmDialog(
                           Desktop.desktop,
@@ -667,22 +668,21 @@ public class VamsasApplication implements SelectionSource, VamsasSource
 
                   if (reply == JvOptionPane.YES_OPTION)
                   {
-                    Cache.log.debug("Prompting for vamsas store filename.");
+                    Console.debug("Prompting for vamsas store filename.");
                     Desktop.instance.vamsasSave_actionPerformed(null);
-                    Cache.log
-                            .debug("Finished attempt at storing document.");
+                    Console.debug("Finished attempt at storing document.");
                   }
-                  Cache.log.debug(
+                  Console.debug(
                           "finished dealing with REQUESTTOCLOSE event.");
                 }
                 else
                 {
-                  Cache.log.debug(
+                  Console.debug(
                           "Ignoring store document request (promptUser==false)");
                 }
               }
             });
-    Cache.log.debug("Added Jalview handler for vamsas document updates.");
+    Console.debug("Added Jalview handler for vamsas document updates.");
   }
 
   public void disableGui(boolean b)
@@ -756,7 +756,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
       } catch (Exception e)
       {
         // Complain to GUI
-        Cache.log.error("Failed to join vamsas session.", e);
+        Console.error("Failed to join vamsas session.", e);
         vclient = null;
       }
       try
@@ -785,16 +785,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 +980,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 +1001,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
           {
             if (vobj2jv == null)
             {
-              Cache.log.warn(
+              Console.warn(
                       "Selection listener still active for dead session.");
               // not in a session.
               return;
@@ -1101,7 +1101,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
               if (sm != null)
               {
                 sm.validate(); // debug
-                Cache.log.debug("Selection Message\n" + sm.getRawMessage());
+                Console.debug("Selection Message\n" + sm.getRawMessage());
                 pm.sendMessage(sm);
               }
             }
@@ -1112,7 +1112,7 @@ public class VamsasApplication implements SelectionSource, VamsasSource
         ssm.addSelectionListener(selecter);
       } catch (Exception e)
       {
-        Cache.log.error("Failed to init Vamsas Picking", e);
+        Console.error("Failed to init Vamsas Picking", e);
       }
     }
   }
index 7a139e2..d9a0dda 100644 (file)
@@ -62,7 +62,7 @@ import compbio.metadata.Parameter;
 import compbio.metadata.Preset;
 import compbio.metadata.PresetManager;
 import compbio.metadata.RunnerConfig;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.OptsAndParamsPage.OptionBox;
 import jalview.gui.OptsAndParamsPage.ParamBox;
 import jalview.util.MessageManager;
@@ -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 (Console.isDebugEnabled())
       {
-        Cache.log.debug("Item state changed for " + setname
+        Console.debug("Item state changed for " + setname
                 + " (handling ? " + !settingDialog + ")");
       }
       if (settingDialog)
index bb5d996..de1be5d 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.gui;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.io.JalviewFileChooser;
 import jalview.io.JalviewFileView;
 import jalview.util.MessageManager;
@@ -106,7 +107,7 @@ public class WsParamSetManager implements ParamManager
         }
       } catch (IOException e)
       {
-        Cache.log.info("Failed to parse parameter file " + pfile
+        Console.info("Failed to parse parameter file " + pfile
                 + " (Check that all JALVIEW_WSPARAMFILES entries are valid!)",
                 e);
       }
@@ -171,7 +172,7 @@ public class WsParamSetManager implements ParamManager
     {
       if (filename != null && !((outfile = new File(filename)).canWrite()))
       {
-        Cache.log.warn("Can't write to " + filename
+        Console.warn("Can't write to " + filename
                 + " - Prompting for new file to write to.");
         filename = null;
       }
@@ -218,7 +219,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 +256,14 @@ public class WsParamSetManager implements ParamManager
         parameterSet.setSourceFile(filename);
       } catch (Exception e)
       {
-        Cache.log.error("Couldn't write parameter file to " + outfile, e);
+        Console.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 +273,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 +291,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 +304,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 +321,7 @@ public class WsParamSetManager implements ParamManager
       }
     } catch (Exception e)
     {
-      Cache.log.error(
+      Console.error(
               "Exception when trying to delete webservice user preset: ",
               e);
     }
index f2d6b96..23b96c9 100644 (file)
@@ -12,7 +12,7 @@ import java.util.Set;
 
 import javax.swing.JTable;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.DBRefSource;
 import jalview.datamodel.PDBEntry;
@@ -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: "
+          Console.warn("Unknown filetype for 3D Beacons Model from: "
                   + strucFormat + " - " + pdbIdStr + " - " + modelPage);
         }
 
index 2b6147f..defc47b 100644 (file)
@@ -33,6 +33,7 @@ import java.util.Map;
 import java.util.TreeMap;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.Desktop;
 import jalview.gui.JvOptionPane;
 import jalview.util.MessageManager;
@@ -131,17 +132,17 @@ public class BackupFiles
       {
         String tempfilename = file.getName();
         File tempdir = file.getParentFile();
-        Cache.trace(
+        Console.trace(
                 "BACKUPFILES [file!=null] attempting to create temp file for "
                         + tempfilename + " in dir " + tempdir);
         temp = File.createTempFile(tempfilename,
                 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
-        Cache.debug(
+        Console.debug(
                 "BACKUPFILES using temp file " + temp.getAbsolutePath());
       }
       else
       {
-        Cache.trace(
+        Console.trace(
                 "BACKUPFILES [file==null] attempting to create default temp file "
                         + DEFAULT_TEMP_FILE + " with extension "
                         + TEMP_FILE_EXT);
@@ -149,29 +150,29 @@ public class BackupFiles
       }
     } catch (IOException e)
     {
-      Cache.error("Could not create temp file to save to (IOException)");
-      Cache.error(e.getMessage());
-      Cache.debug(Cache.getStackTraceString(e));
+      Console.error("Could not create temp file to save to (IOException)");
+      Console.error(e.getMessage());
+      Console.debug(Cache.getStackTraceString(e));
     } catch (Exception e)
     {
-      Cache.error("Exception creating temp file for saving");
-      Cache.debug(Cache.getStackTraceString(e));
+      Console.error("Exception creating temp file for saving");
+      Console.debug(Cache.getStackTraceString(e));
     }
     this.setTempFile(temp);
   }
 
   public static void classInit()
   {
-    Cache.initLogger();
-    Cache.trace("BACKUPFILES classInit");
+    Console.initLogger();
+    Console.trace("BACKUPFILES classInit");
     boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
     setEnabled(e);
-    Cache.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
+    Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
     BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
             .getSavedBackupEntry();
-    Cache.trace("BACKUPFILES preset scheme " + bfpe.toString());
+    Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
     setConfirmDelete(bfpe.confirmDelete);
-    Cache.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
+    Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
   }
 
   public static void setEnabled(boolean flag)
@@ -215,9 +216,9 @@ public class BackupFiles
       path = this.getTempFile().getCanonicalPath();
     } catch (IOException e)
     {
-      Cache.error("IOException when getting Canonical Path of temp file '"
+      Console.error("IOException when getting Canonical Path of temp file '"
               + this.getTempFile().getName() + "'");
-      Cache.debug(Cache.getStackTraceString(e));
+      Console.debug(Cache.getStackTraceString(e));
     }
     return path;
   }
@@ -253,7 +254,7 @@ public class BackupFiles
             || suffix.length() == 0)
     {
       // nothing to do
-      Cache.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
+      Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
               + "filename: " + (file != null ? file.getName() : "null")
               + ", " + "file exists: " + file.exists() + ", " + "enabled: "
               + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
@@ -261,7 +262,7 @@ public class BackupFiles
       return true;
     }
 
-    Cache.trace("BACKUPFILES rollBackupFiles starting");
+    Console.trace("BACKUPFILES rollBackupFiles starting");
 
     String dir = "";
     File dirFile;
@@ -269,18 +270,18 @@ public class BackupFiles
     {
       dirFile = file.getParentFile();
       dir = dirFile.getCanonicalPath();
-      Cache.trace("BACKUPFILES dir: " + dir);
+      Console.trace("BACKUPFILES dir: " + dir);
     } catch (Exception e)
     {
-      Cache.error("Could not get canonical path for file '" + file + "'");
-      Cache.error(e.getMessage());
-      Cache.debug(Cache.getStackTraceString(e));
+      Console.error("Could not get canonical path for file '" + file + "'");
+      Console.error(e.getMessage());
+      Console.debug(Cache.getStackTraceString(e));
       return false;
     }
     String filename = file.getName();
     String basename = filename;
 
-    Cache.trace("BACKUPFILES filename is " + filename);
+    Console.trace("BACKUPFILES filename is " + filename);
     boolean ret = true;
     // Create/move backups up one
 
@@ -292,11 +293,11 @@ public class BackupFiles
     File[] backupFiles = dirFile.listFiles(bff);
     int nextIndexNum = 0;
 
-    Cache.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
+    Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
     if (backupFiles.length == 0)
     {
       // No other backup files. Just need to move existing file to backupfile_1
-      Cache.trace(
+      Console.trace(
               "BACKUPFILES no existing backup files, setting index to 1");
       nextIndexNum = 1;
     }
@@ -310,7 +311,7 @@ public class BackupFiles
       if (reverseOrder)
       {
         // backup style numbering
-        Cache.trace("BACKUPFILES rolling files in reverse order");
+        Console.trace("BACKUPFILES rolling files in reverse order");
 
         int tempMax = noMax ? -1 : max;
         // noMax == true means no limits
@@ -342,7 +343,7 @@ public class BackupFiles
             // no "oldest" file to delete
             previousFile = backupfile_n;
             fileToBeDeleted = null;
-            Cache.trace("BACKUPFILES No oldest file to delete");
+            Console.trace("BACKUPFILES No oldest file to delete");
             continue;
           }
 
@@ -353,9 +354,9 @@ public class BackupFiles
             File replacementFile = backupfile_n;
             long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
             long replacementFileLMT = replacementFile.lastModified();
-            Cache.trace("BACKUPFILES fileToBeDeleted is "
+            Console.trace("BACKUPFILES fileToBeDeleted is "
                     + fileToBeDeleted.getAbsolutePath());
-            Cache.trace("BACKUPFILES replacementFile is "
+            Console.trace("BACKUPFILES replacementFile is "
                     + backupfile_n.getAbsolutePath());
 
             try
@@ -369,7 +370,7 @@ public class BackupFiles
                         .format(fileToBeDeletedLMT);
                 String replacementFileLMTString = sdf
                         .format(replacementFileLMT);
-                Cache.warn("WARNING! I am set to delete backupfile "
+                Console.warn("WARNING! I am set to delete backupfile "
                         + fileToBeDeleted.getName()
                         + " has modification time "
                         + fileToBeDeletedLMTString
@@ -380,7 +381,7 @@ public class BackupFiles
 
                 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
                         replacementFile, true);
-                Cache.trace("BACKUPFILES " + (delete ? "confirmed" : "not")
+                Console.trace("BACKUPFILES " + (delete ? "confirmed" : "not")
                         + " deleting file "
                         + fileToBeDeleted.getAbsolutePath()
                         + " which is newer than "
@@ -393,7 +394,7 @@ public class BackupFiles
                 }
                 else
                 {
-                  Cache.debug("BACKUPFILES moving "
+                  Console.debug("BACKUPFILES moving "
                           + fileToBeDeleted.getAbsolutePath() + " to "
                           + oldestTempFile.getAbsolutePath());
                   moveFileToFile(fileToBeDeleted, oldestTempFile);
@@ -401,7 +402,7 @@ public class BackupFiles
               }
               else
               {
-                Cache.debug("BACKUPFILES going to move "
+                Console.debug("BACKUPFILES going to move "
                         + fileToBeDeleted.getAbsolutePath() + " to "
                         + oldestTempFile.getAbsolutePath());
                 moveFileToFile(fileToBeDeleted, oldestTempFile);
@@ -410,10 +411,10 @@ public class BackupFiles
 
             } catch (Exception e)
             {
-              Cache.error(
+              Console.error(
                       "Error occurred, probably making new temp file for '"
                               + fileToBeDeleted.getName() + "'");
-              Cache.error(Cache.getStackTraceString(e));
+              Console.error(Cache.getStackTraceString(e));
             }
 
             // reset
@@ -455,12 +456,12 @@ public class BackupFiles
           }
           bfsb.append(backupFiles[i].getName());
         }
-        Cache.trace("BACKUPFILES backupFiles: " + bfsb.toString());
+        Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
 
         // noMax == true means keep all backup files
         if ((!noMax) && bfTreeMap.size() >= max)
         {
-          Cache.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
+          Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
                   + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
           // need to delete some files to keep number of backups to designated
           // max.
@@ -470,7 +471,7 @@ public class BackupFiles
           int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
                   ? bfTreeMap.size() - max + 1
                   : 0;
-          Cache.trace("BACKUPFILES numToDelete: " + numToDelete);
+          Console.trace("BACKUPFILES numToDelete: " + numToDelete);
           // the "replacement" file is the latest backup file being kept (it's
           // not replacing though)
           File replacementFile = numToDelete < backupFiles.length
@@ -483,7 +484,7 @@ public class BackupFiles
             File fileToBeDeleted = backupFiles[i];
             boolean delete = true;
 
-            Cache.trace("BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
+            Console.trace("BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
 
             boolean newer = false;
             if (replacementFile != null)
@@ -499,7 +500,7 @@ public class BackupFiles
                 String replacementFileLMTString = sdf
                         .format(replacementFileLMT);
 
-                Cache.warn("WARNING! I am set to delete backupfile '"
+                Console.warn("WARNING! I am set to delete backupfile '"
                         + fileToBeDeleted.getName()
                         + "' has modification time "
                         + fileToBeDeletedLMTString
@@ -514,14 +515,14 @@ public class BackupFiles
                 {
                   // User has confirmed delete -- no need to add it to the list
                   fileToBeDeleted.delete();
-                  Cache.debug("BACKUPFILES deleting fileToBeDeleted: "
+                  Console.debug("BACKUPFILES deleting fileToBeDeleted: "
                           + fileToBeDeleted);
                   delete = false;
                 }
                 else
                 {
                   // keeping file, nothing to do!
-                  Cache.debug("BACKUPFILES keeping fileToBeDeleted: "
+                  Console.debug("BACKUPFILES keeping fileToBeDeleted: "
                           + fileToBeDeleted);
                 }
               }
@@ -529,7 +530,7 @@ public class BackupFiles
             if (delete)
             {
               addDeleteFile(fileToBeDeleted);
-              Cache.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
+              Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
                       + fileToBeDeleted);
             }
 
@@ -545,16 +546,16 @@ public class BackupFiles
     String latestBackupFilename = dir + File.separatorChar
             + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
                     suffix, digits);
-    Cache.trace("BACKUPFILES Moving old file [" + file
+    Console.trace("BACKUPFILES Moving old file [" + file
             + "] to latestBackupFilename [" + latestBackupFilename + "]");
     // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
     // be conditional (short-circuit)
     ret = ret & moveFileToFile(file, new File(latestBackupFilename));
-    Cache.debug("BACKUPFILES moving " + file + " to " + latestBackupFilename
+    Console.debug("BACKUPFILES moving " + file + " to " + latestBackupFilename
             + " was " + (ret ? "" : "NOT ") + "successful");
     if (tidyUp)
     {
-      Cache.debug("BACKUPFILES tidying up files");
+      Console.debug("BACKUPFILES tidying up files");
       tidyUpFiles();
     }
 
@@ -610,7 +611,7 @@ public class BackupFiles
         saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
       } catch (Exception e)
       {
-        Cache.error(
+        Console.error(
                 "Error when confirming to keep backup file newer than other backup files.");
         e.printStackTrace();
       }
@@ -720,10 +721,10 @@ public class BackupFiles
         for (int i = 0; i < deleteFiles.size(); i++)
         {
           File fileToDelete = deleteFiles.get(i);
-          Cache.trace("BACKUPFILES about to delete fileToDelete:"
+          Console.trace("BACKUPFILES about to delete fileToDelete:"
                   + fileToDelete);
           fileToDelete.delete();
-          Cache.warn("deleted '" + fileToDelete.getName() + "'");
+          Console.warn("deleted '" + fileToDelete.getName() + "'");
         }
       }
 
@@ -832,7 +833,7 @@ public class BackupFiles
       dirFile = file.getParentFile();
     } catch (Exception e)
     {
-      Cache.error("Could not get canonical path for file '" + file + "'");
+      Console.error("Could not get canonical path for file '" + file + "'");
       return new TreeMap<>();
     }
 
@@ -873,14 +874,14 @@ public class BackupFiles
     int pos = deleteFiles.indexOf(fileToBeDeleted);
     if (pos > -1)
     {
-      Cache.debug("BACKUPFILES not adding file "
+      Console.debug("BACKUPFILES not adding file "
               + fileToBeDeleted.getAbsolutePath()
               + " to the delete list (already at index" + pos + ")");
       return true;
     }
     else
     {
-      Cache.debug("BACKUPFILES adding file "
+      Console.debug("BACKUPFILES adding file "
               + fileToBeDeleted.getAbsolutePath() + " to the delete list");
       deleteFiles.add(fileToBeDeleted);
     }
@@ -889,31 +890,31 @@ public class BackupFiles
 
   public static boolean moveFileToFile(File oldFile, File newFile)
   {
-    Cache.initLogger();
+    Console.initLogger();
     boolean ret = false;
     Path oldPath = Paths.get(oldFile.getAbsolutePath());
     Path newPath = Paths.get(newFile.getAbsolutePath());
     try
     {
       // delete destination file - not usually necessary but Just In Case...
-      Cache.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
+      Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
       newFile.delete();
-      Cache.trace("BACKUPFILES moving " + oldFile.getAbsolutePath() + " to "
+      Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath() + " to "
               + newFile.getAbsolutePath());
       Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
       ret = true;
-      Cache.trace("BACKUPFILES move seems to have succeeded");
+      Console.trace("BACKUPFILES move seems to have succeeded");
     } catch (IOException e)
     {
-      Cache.warn("Could not move file '" + oldPath.toString() + "' to '"
+      Console.warn("Could not move file '" + oldPath.toString() + "' to '"
               + newPath.toString() + "'");
-      Cache.error(e.getMessage());
-      Cache.debug(Cache.getStackTraceString(e));
+      Console.error(e.getMessage());
+      Console.debug(Cache.getStackTraceString(e));
       ret = false;
     } catch (Exception e)
     {
-      Cache.error(e.getMessage());
-      Cache.debug(Cache.getStackTraceString(e));
+      Console.error(e.getMessage());
+      Console.debug(Cache.getStackTraceString(e));
       ret = false;
     }
     return ret;
index ff8a5e6..3c70b82 100644 (file)
@@ -25,6 +25,7 @@ import java.util.Map;
 import java.util.StringTokenizer;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.util.MessageManager;
 
 public class BackupFilesPresetEntry
@@ -124,7 +125,7 @@ public class BackupFilesPresetEntry
       confirmDelete = Boolean.valueOf(st.nextToken());
     } catch (Exception e)
     {
-      Cache.log.error("Error parsing backupfiles scheme '" + line + "'");
+      Console.error("Error parsing backupfiles scheme '" + line + "'");
     }
 
     return new BackupFilesPresetEntry(suffix, digits, reverse, keepAll,
index 9db3df2..48988cf 100644 (file)
@@ -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");
 
index 64943b2..e8ce34b 100644 (file)
@@ -12,7 +12,7 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.TreeMap;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.DBRefSource;
 import jalview.datamodel.FeatureProperties;
@@ -83,8 +83,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile
 
   /**
    * Truncates (if necessary) the exon intervals to match 3 times the length of
-   * the protein; also accepts 3 bases longer (for stop codon not included in
-   * protein)
+   * the protein(including truncation for stop codon included in exon)
    * 
    * @param proteinLength
    * @param exon
@@ -102,11 +101,9 @@ public abstract class EMBLLikeFlatFile extends AlignFile
     int exonLength = MappingUtils.getLength(Arrays.asList(exon));
 
     /*
-     * if exon length matches protein, or is shorter, or longer by the 
-     * length of a stop codon (3 bases), then leave it unchanged
+     * if exon length matches protein, or is shorter, then leave it unchanged
      */
-    if (expectedCdsLength >= exonLength
-            || expectedCdsLength == exonLength - 3)
+    if (expectedCdsLength >= exonLength)
     {
       return exon;
     }
@@ -291,7 +288,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile
       int slashPos = line.indexOf('/');
       if (slashPos == -1)
       {
-        Cache.log.error("Unexpected EMBL line ignored: " + line);
+        Console.error("Unexpected EMBL line ignored: " + line);
         line = nextLine();
         continue;
       }
@@ -321,7 +318,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
+          Console.error("Invalid codon_start in XML for " + this.accession
                   + ": " + e.getMessage());
         }
       }
@@ -357,7 +354,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile
     }
     else
     {
-      Cache.log.error("Ignoring CDS feature with no protein_id for "
+      Console.error("Ignoring CDS feature with no protein_id for "
               + sourceDb + ":" + accession);
     }
 
@@ -382,7 +379,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile
   {
     if (this.accession == null || this.sequenceString == null)
     {
-      Cache.log.error("Failed to parse data from EMBL");
+      Console.error("Failed to parse data from EMBL");
       return;
     }
 
@@ -584,7 +581,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(
+      Console.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 +591,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");
+        Console.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");
+        Console.warn("Assuming stop codon at end of cDNA fragment");
         mappedDnaEnd = dna.getEnd() - 3;
       }
 
@@ -673,7 +670,7 @@ public abstract class EMBLLikeFlatFile extends AlignFile
       return MappingUtils.rangeListToArray(ranges);
     } catch (ParseException e)
     {
-      Cache.log.warn(
+      Console.warn(
               String.format("Not parsing inexact CDS location %s in ENA %s",
                       location, accession));
       return new int[] {};
@@ -718,7 +715,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
+        Console.error("Ignoring bad EMBL line for " + this.accession
                 + ": " + line);
         break;
       }
index 7808d1a..75b8981 100644 (file)
@@ -2,7 +2,7 @@ package jalview.io;
 
 import java.io.IOException;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.DBRefEntry;
 import jalview.util.DBRefUtils;
 
@@ -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);
+        Console.error("bad length read in flatfile, line: " + line);
       }
     }
 
index c7c1d71..3d2dded 100755 (executable)
@@ -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)
             {
index 5fd33be..2dec559 100755 (executable)
@@ -41,7 +41,7 @@ import jalview.api.AlignExportSettingsI;
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureSettingsModelI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
 
@@ -225,7 +225,7 @@ public class FileParse
   {
     if (!input.markSupported())
     {
-      Cache.log.error(
+      Console.error(
               "FileParse.izGzipStream: input stream must support mark/reset");
       return false;
     }
index 31751f5..00920db 100755 (executable)
@@ -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
index b8241c8..81773bc 100644 (file)
@@ -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
index a56f2af..d66fe6c 100755 (executable)
@@ -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 */
index 62b723d..9ffdf21 100644 (file)
@@ -209,12 +209,27 @@ public class SequenceAnnotationReport
      * if this is a virtual features, convert begin/end to the
      * coordinates of the sequence it is mapped to
      */
-    int[] beginRange = null;
-    int[] endRange = null;
+    int[] beginRange = null; // feature start in local coordinates
+    int[] endRange = null; // feature end in local coordinates
     if (mf != null)
     {
-      beginRange = mf.getMappedPositions(begin, begin);
-      endRange = mf.getMappedPositions(end, end);
+      if (feature.isContactFeature())
+      {
+        /*
+         * map start and end points individually
+         */
+        beginRange = mf.getMappedPositions(begin, begin);
+        endRange = begin == end ? beginRange
+                : mf.getMappedPositions(end, end);
+      }
+      else
+      {
+        /*
+         * map the feature extent
+         */
+        beginRange = mf.getMappedPositions(begin, end);
+        endRange = beginRange;
+      }
       if (beginRange == null || endRange == null)
       {
         // something went wrong
index c8c9c8a..cff328b 100644 (file)
@@ -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)
   {
index 2fc526b..5365dfa 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.io;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.GraphLine;
@@ -183,7 +183,7 @@ public class VamsasAppDatastore
           Vobject obj = getjv2vObj(seqsetidobj);
           if (obj != null && !(obj instanceof Alignment))
           {
-            Cache.log.warn(
+            Console.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 "
+          Console.warn("Unexpected mapping for Jalview String Object ID "
                   + seqsetidobj + " to another jalview dataset object "
                   + seqsetidobj);
         }
       }
     }
 
-    if (Cache.log.isDebugEnabled())
+    if (Console.isDebugEnabled())
     {
-      Cache.log.debug(
+      Console.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(
+      Console.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 "
+        Console.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(
+      Console.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(
+      Console.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);
+    Console.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.");
+        Console.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 "
+        Console.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(
+            Console.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(
+                Console.info(
                         "update alignment sequence annotation. not yet implemented.");
               }
               else
               {
                 // verify annotation - update (perhaps)
-                Cache.log.info(
+                Console.info(
                         "updated alignment sequence annotation added.");
               }
             }
@@ -889,7 +889,7 @@ public class VamsasAppDatastore
     }
     if (getjv2vObj(jvalsq.getDatasetSequence()) == null)
     {
-      Cache.log.warn(
+      Console.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 && Console.isDebugEnabled())
       {
-        Cache.log.debug(
+        Console.debug(
                 "Updating apparently edited sequence " + alseq.getName());
       }
     }
@@ -986,7 +986,7 @@ public class VamsasAppDatastore
       }
       else
       {
-        Cache.log.error(
+        Console.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(
+                Console.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(
+              Console.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)
+      Console.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(
+        Console.error(
                 "Couldn't update jalview client application data. Giving up - local settings probably lost.",
                 e);
       }
     }
     else
     {
-      jalview.bin.Cache.log.error(
+      Console.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");
+          Console.debug("Initialising new jalview dataset fields");
           newds = true;
           dsseqs = new Vector();
         }
         else
         {
-          Cache.log.debug("Update jalview dataset from vamsas.");
+          Console.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.");
+          Console.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(
+                Console.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(
+                  Console.warn(
                           "Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
                 }
               }
             }
             else
             {
-              Cache.log.warn(
+              Console.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(
+                      Console.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 "
+              Console.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(
+                  Console.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(
+                    Console.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 "
+              Console.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 (Console.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);
+                    Console.warn("update of labels failed.", e);
                   }
                 }
                 else
                 {
-                  Cache.log.warn("Cannot create tree for tree " + t
+                  Console.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);
+            Console.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.");
+                Console.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(
+                Console.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(
+              Console.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
+          Console.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");
+            Console.warn("Failed to parse threshold property");
           }
           if (val != null)
           {
@@ -2289,14 +2288,14 @@ public class VamsasAppDatastore
     }
     if (parsedRangeAnnotation == null)
     {
-      Cache.log.debug(
+      Console.debug(
               "Inserting empty annotation row elements for a whole-alignment annotation.");
     }
     else
     {
       if (parsedRangeAnnotation[3] != null)
       {
-        Cache.log.warn("Ignoring 'After' annotation row in "
+        Console.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()
+        Console.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(
+        Console.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.");
+        Console.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(
+        Console.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(
+                Console.warn(
                         "NO Vamsas Binding for local sequence! NOT CREATING MAPPING FOR "
                                 + dmps[smp].getDisplayId(true) + " to "
                                 + mps[smp].getTo().getName());
index 56d9fa4..ed262c5 100644 (file)
  */
 package jalview.io.vamsas;
 
-import jalview.bin.Cache;
-import jalview.io.VamsasAppDatastore;
-import jalview.util.MessageManager;
-
 import java.util.Enumeration;
 import java.util.Hashtable;
 import java.util.IdentityHashMap;
 import java.util.Vector;
 
+import jalview.bin.Console;
+import jalview.io.VamsasAppDatastore;
+import jalview.log.JLoggerLog4j;
+import jalview.util.MessageManager;
 import uk.ac.vamsas.client.IClientDocument;
 import uk.ac.vamsas.client.Vobject;
 import uk.ac.vamsas.client.VorbaId;
@@ -60,7 +60,7 @@ public abstract class DatastoreItem
   /**
    * shared log instance
    */
-  protected static org.apache.log4j.Logger log = org.apache.log4j.Logger
+  protected static JLoggerLog4j log = JLoggerLog4j
           .getLogger(DatastoreItem.class);
 
   /**
@@ -74,9 +74,9 @@ public abstract class DatastoreItem
     {
       return cdoc.getObject((VorbaId) jv2vobj.get(jvobj));
     }
-    if (Cache.log.isDebugEnabled())
+    if (Console.isDebugEnabled())
     {
-      Cache.log.debug(
+      Console.debug(
               "Returning null VorbaID binding for jalview object " + jvobj);
     }
     return null;
@@ -95,7 +95,7 @@ public abstract class DatastoreItem
     if (id == null)
     {
       id = cdoc.registerObject(vobj);
-      Cache.log.debug(
+      Console.debug(
               "Registering new object and returning null for getvObj2jv");
       return null;
     }
@@ -122,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 "
+        Console.error("Failed to get id for "
                 + (vobj.isRegisterable() ? "registerable"
                         : "unregisterable")
                 + " object " + vobj);
@@ -131,7 +131,7 @@ public abstract class DatastoreItem
     if (vobj2jv.containsKey(vobj.getVorbaId())
             && !(vobj2jv.get(vobj.getVorbaId())).equals(jvobj))
     {
-      Cache.log.debug(
+      Console.debug(
               "Warning? Overwriting existing vamsas id binding for "
                       + vobj.getVorbaId(),
               new Exception(MessageManager.getString(
@@ -140,20 +140,20 @@ public abstract class DatastoreItem
     else if (jv2vobj.containsKey(jvobj)
             && !((VorbaId) jv2vobj.get(jvobj)).equals(vobj.getVorbaId()))
     {
-      Cache.log.debug(
+      Console.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);
+    Console.debug("Binding " + vobj.getVorbaId() + " to " + jvobj);
     vobj2jv.put(vobj.getVorbaId(), jvobj);
     // JBPNote - better implementing a hybrid invertible hash.
     jv2vobj.put(jvobj, vobj.getVorbaId());
@@ -171,8 +171,8 @@ public abstract class DatastoreItem
   {
     if (this.jvobj != null && this.vobj != null)
     {
-      Cache.log.debug("updating dsobj registry. ("
-              + this.getClass().getName() + ")");
+      Console.debug("updating dsobj registry. (" + this.getClass().getName()
+              + ")");
     }
     this.jvobj = jvobj;
     this.vobj = vobj;
index b53de08..233685b 100644 (file)
@@ -24,9 +24,11 @@ import java.util.IdentityHashMap;
 import java.util.Iterator;
 import java.util.Map;
 
+import jalview.log.JLoggerLog4j;
+
 public class DatastoreRegistry implements AutoCloseable
 {
-  protected static org.apache.log4j.Logger log = org.apache.log4j.Logger
+  protected static JLoggerLog4j log = JLoggerLog4j
           .getLogger(DatastoreRegistry.class);
 
   /**
index bdef00f..91bf666 100644 (file)
@@ -20,6 +20,7 @@
  */
 package jalview.io.vamsas;
 
+import jalview.bin.Console;
 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(
+      Console.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: "
+        Console.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()
+    Console.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: "
+        Console.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(
+        Console.debug(
                 "Ignoring mapless DbRef.Map " + jvobj.getSrcAccString());
       }
     }
index 0fed7d7..bd25c62 100644 (file)
@@ -20,6 +20,7 @@
  */
 package jalview.io.vamsas;
 
+import jalview.bin.Console;
 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 "
+      Console.warn("using default mapping length of 1:1 for map "
                       + (map.isRegistered() ? map.getVorbaId().toString()
                               : ("<no Id registered> " + map.toString())));
     }
index f8d86d5..e6302fc 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.io.vamsas;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.io.VamsasAppDatastore;
@@ -97,7 +97,7 @@ public class Sequencefeature extends Rangetype
     DataSetAnnotations dsa = (DataSetAnnotations) vobj;
     if (dsa.getSeqRefCount() != 1)
     {
-      Cache.log.warn("Not binding " + dsa.getVorbaId()
+      Console.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(
+      Console.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.");
+        Console.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()
+      Console.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(
+      Console.debug(
               "About to destroy complex annotation in vamsas document mapped to sequence feature ("
                       + dsa.getVorbaId() + ")");
     }
index 0a582e5..5a172fe 100644 (file)
@@ -20,6 +20,7 @@
  */
 package jalview.io.vamsas;
 
+import jalview.bin.Console;
 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
+      Console.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
+      Console.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(
+      Console.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(
+      Console.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(
+    Console.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!");
+    Console.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");
+    Console.error("Not implemented: Update DBRef Mapping from Jalview");
   }
 
   private void update(jalview.datamodel.Mapping mjvmapping,
           SequenceMapping sequenceMapping)
   {
-    jalview.bin.Cache.log.error(
+    Console.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");
+      Console.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(
+      Console.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 (Console.isDebugEnabled())
       {
-        jalview.bin.Cache.log.debug("Not matching conjugate refs for "
+        Console.debug("Not matching conjugate refs for "
                 + from.getName() + " and " + to.getName());
       }
       return;
     }
-    if (jalview.bin.Cache.log.isDebugEnabled())
+    if (Console.isDebugEnabled())
     {
-      jalview.bin.Cache.log.debug("Matching conjugate refs for "
+      Console.debug("Matching conjugate refs for "
               + from.getName() + " and " + to.getName());
     }
     List<DBRefEntry> 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;
       // }
index 00e4fbc..1b7a8bf 100644 (file)
@@ -22,7 +22,7 @@ package jalview.io.vamsas;
 
 import jalview.analysis.TreeBuilder;
 import jalview.analysis.TreeModel;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.BinaryNode;
@@ -128,7 +128,7 @@ public class Tree extends DatastoreItem
       }
     } catch (Exception e)
     {
-      Cache.log.warn("Problems parsing treefile '"
+      Console.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(
+    Console.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());
+    Console.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());
+    Console.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(
+      Console.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(
+      Console.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(
+          Console.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.");
+            Console.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(
+    Console.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);
+      Console.debug("Failed to parse newick tree string", e);
     }
     return false;
   }
index dadb532..29b3004 100644 (file)
@@ -51,6 +51,7 @@ import htsjdk.variant.vcf.VCFInfoHeaderLine;
 import jalview.analysis.Dna;
 import jalview.api.AlignViewControllerGuiI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.GeneLociI;
 import jalview.datamodel.Mapping;
@@ -314,7 +315,7 @@ public class VCFLoader
     VCFHeaderLine headerLine = header.getOtherHeaderLine(VCFHeader.REFERENCE_KEY);
     if (headerLine == null)
     {
-      Cache.log.error("VCF reference header not found");
+      Console.error("VCF reference header not found");
       return null;
     }
     String ref = headerLine.getValue();
@@ -336,7 +337,7 @@ public class VCFLoader
     }
     else
     {
-      Cache.log.error("VCF reference not found: " + ref);
+      Console.error("VCF reference not found: " + ref);
     }
 
     return seq;
@@ -429,7 +430,7 @@ public class VCFLoader
   {
     if (reference == null)
     {
-      Cache.log.error("No VCF ##reference found, defaulting to "
+      Console.error("No VCF ##reference found, defaulting to "
               + DEFAULT_REFERENCE + ":" + DEFAULT_SPECIES);
       reference = DEFAULT_REFERENCE; // default to GRCh37 if not specified
     }
@@ -775,7 +776,7 @@ public class VCFLoader
     GeneLociI seqCoords = seq.getGeneLoci();
     if (seqCoords == null)
     {
-      Cache.log.warn(String.format(
+      Console.warn(String.format(
               "Can't query VCF for %s as chromosome coordinates not known",
               seq.getName()));
       return null;
@@ -790,7 +791,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()
+      Console.warn("No VCF loaded to " + seq.getName()
               + " as species not matched");
       return null;
     }
@@ -820,7 +821,7 @@ public class VCFLoader
               vcfAssembly);
       if (newRange == null)
       {
-        Cache.log.error(
+        Console.error(
                 String.format("Failed to map %s:%s:%s:%d:%d to %s", species,
                         chromosome, seqRef, range[0], range[1],
                         vcfAssembly));
@@ -920,7 +921,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);
+        Console.error(msg);
       }
     }
 
@@ -1382,7 +1383,7 @@ public class VCFLoader
     VCFInfoHeaderLine infoHeader = header.getInfoHeaderLine(infoId);
     if (infoHeader == null)
     {
-      Cache.log.error("Field " + infoId + " has no INFO header");
+      Console.error("Field " + infoId + " has no INFO header");
       return false;
     }
     VCFHeaderLineType infoType = infoHeader.getType();
@@ -1423,7 +1424,7 @@ public class VCFLoader
     if (!badData.contains(token))
     {
       badData.add(token);
-      Cache.log.error(String.format("Invalid VCF data at %s:%d %s=%s",
+      Console.error(String.format("Invalid VCF data at %s:%d %s=%s",
               variant.getContig(), variant.getStart(), infoId, value));
     }
   }
index 6a4d0f8..16b57a4 100644 (file)
@@ -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 (file)
index 1b2b676..0000000
+++ /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 (file)
index f1aca45..0000000
+++ /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 (file)
index e467e36..0000000
+++ /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 <http://www.gnu.org/licenses/>.
- * The Jalview Authors are detailed in the 'AUTHORS' file.
- */
-package jalview.javascript.log4j;
-
-import jalview.javascript.log4j.spi.LoggingEvent;
-import jalview.javascript.log4j.spi.OptionHandler;
-
-import org.apache.log4j.PatternLayout;
-//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
-   * <code>null</code>.
-   */
-  public String getHeader()
-  {
-    return null;
-  }
-
-  /**
-   * Returns the footer for the layout format. The base class returns
-   * <code>null</code>.
-   */
-  public String getFooter()
-  {
-    return null;
-  }
-
-  /**
-   * If the layout handles the throwable object contained within
-   * {@link LoggingEvent}, then the layout should return <code>false</code>.
-   * Otherwise, if the layout ignores throwable object, then the layout should
-   * return <code>true</code>. If ignoresThrowable is true, the appender is
-   * responsible for rendering the throwable.
-   * <p>
-   * The {@link SimpleLayout}, {@link TTCCLayout}, {@link PatternLayout} all
-   * return <code>true</code>. The {@link org.apache.log4j.xml.XMLLayout}
-   * returns <code>false</code>.
-   * 
-   * @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 (file)
index 582f2de..0000000
+++ /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
- * <code>OFF</code>, <code>FATAL</code>, <code>ERROR</code>, <code>WARN</code>,
- * <code>INFO</code>, <code>DEBUG</code> and <code>ALL</code>.
- * 
- * <p>
- * The <code>Level</code> class may be subclassed to define a larger level set.
- * </p>
- * 
- * @author Ceki G&uuml;lc&uuml;
- */
-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 <code>OFF</code> 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 <code>FATAL</code> 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 <code>ERROR</code> 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 <code>WARN</code> level designates potentially harmful situations.
-   */
-  final static public Level WARN = new Level(WARN_INT, WARN_NAME, 4);
-
-  /**
-   * The <code>INFO</code> 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 <code>DEBUG</code> 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 <code>TRACE</code> Level designates finer-grained informational events
-   * than the <code>DEBUG</code level.
-   * 
-   * @since 1.2.12
-   */
-  public static final Level TRACE = new Level(TRACE_INT, TRACE_NAME, 7);
-
-  /**
-   * The <code>ALL</code> 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 <code>defaultLevel</code>.
-   */
-  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 (file)
index bb7eb34..0000000
+++ /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 <http://www.gnu.org/licenses/>.
- * 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<String, Logger> 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 (file)
index 2ace1eb..0000000
+++ /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 <Simon.Kitching@orange.ch>
-
-package jalview.javascript.log4j;
-
-/**
-   <font color="#AA4444">Refrain from using this class directly, use
-   the {@link Level} class instead</font>.
-
-   @author Ceki G&uuml;lc&uuml; */
-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 <code>true</code> if this level has a higher or equal
-     level than the level passed as argument, <code>false</code>
-     otherwise.  
-     
-     <p>You should think twice before overriding the default
-     implementation of <code>isGreaterOrEqual</code> 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 (file)
index 9e5cbba..0000000
+++ /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 <http://www.gnu.org/licenses/>.
- * 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 (file)
index 1a015f2..0000000
+++ /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 (file)
index 669ae52..0000000
+++ /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 <http://www.gnu.org/licenses/>.
- * 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 (file)
index 9cd0f01..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-package jalview.javascript.log4j.spi;
-
-public interface OptionHandler
-{
-
-  void activateOptions();
-
-}
index 6685c67..6aaba84 100755 (executable)
@@ -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("<html>" + 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
index debb2ab..d281c8d 100755 (executable)
@@ -43,6 +43,7 @@ import java.util.List;
 
 import javax.swing.AbstractCellEditor;
 import javax.swing.BorderFactory;
+import javax.swing.BoxLayout;
 import javax.swing.ButtonGroup;
 import javax.swing.DefaultListCellRenderer;
 import javax.swing.JButton;
@@ -54,6 +55,7 @@ import javax.swing.JPanel;
 import javax.swing.JPasswordField;
 import javax.swing.JRadioButton;
 import javax.swing.JScrollPane;
+import javax.swing.JSlider;
 import javax.swing.JSpinner;
 import javax.swing.JTabbedPane;
 import javax.swing.JTable;
@@ -75,6 +77,8 @@ import javax.swing.table.TableCellEditor;
 import javax.swing.table.TableCellRenderer;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
+import jalview.bin.MemorySetting;
 import jalview.fts.core.FTSDataColumnPreferences;
 import jalview.fts.core.FTSDataColumnPreferences.PreferenceSource;
 import jalview.fts.service.pdb.PDBFTSRestClient;
@@ -89,6 +93,7 @@ import jalview.io.BackupFilesPresetEntry;
 import jalview.io.IntKeyStringValueEntry;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
+import jalview.util.StringUtils;
 
 /**
  * Base class for the Preferences panel.
@@ -379,6 +384,30 @@ public class GPreferences extends JPanel
 
   private JLabel messageLabel = new JLabel("", JLabel.CENTER);
 
+  /*
+   * Startup tab components
+   */
+
+  protected JCheckBox customiseMemorySetting = new JCheckBox();
+
+  protected JLabel exampleMemoryLabel = new JLabel();
+
+  protected JTextArea exampleMemoryMessageTextArea = new JTextArea();
+
+  protected JLabel maxMemoryLabel = new JLabel();
+
+  protected JLabel jvmMemoryPercentLabel = new JLabel();
+
+  protected JSlider jvmMemoryPercentSlider = new JSlider();
+
+  protected JLabel jvmMemoryPercentDisplay = new JLabel();
+
+  protected JLabel jvmMemoryMaxLabel = new JLabel();
+
+  protected JTextField jvmMemoryMaxTextField = new JTextField(null, 8);
+
+  protected JComboBox<Object> lafCombo = new JComboBox<>();
+
   /**
    * Creates a new GPreferences object.
    */
@@ -440,6 +469,9 @@ public class GPreferences extends JPanel
     tabbedPane.add(initEditingTab(),
             MessageManager.getString("label.editing"));
 
+    tabbedPane.add(initStartupTab(),
+            MessageManager.getString("label.startup"));
+
     /*
      * See WsPreferences for the real work of configuring this tab.
      */
@@ -2200,6 +2232,19 @@ public class GPreferences extends JPanel
     updateBackupFilesExampleLabel();
   }
 
+  /*
+   * Load the saved Memory settings
+   */
+  protected void loadLastSavedMemorySettings()
+  {
+    customiseMemorySetting.setSelected(
+            Cache.getDefault(MemorySetting.CUSTOMISED_SETTINGS, false));
+    jvmMemoryPercentSlider
+            .setValue(Cache.getDefault(MemorySetting.MEMORY_JVMMEMPC, 90));
+    jvmMemoryMaxTextField.setText(
+            Cache.getDefault(MemorySetting.MEMORY_JVMMEMMAX, "32g"));
+  }
+
   private boolean warnAboutSuffixReverseChange()
   {
     BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
@@ -2217,6 +2262,285 @@ public class GPreferences extends JPanel
             && nowSuffixTemplate.equals(savedSuffixTemplate);
   }
 
+  /* Initialises the Startup tabbed panel.
+   * 
+   * @return
+   * */
+
+  private JPanel initStartupTab()
+  {
+    JPanel startupTab = new JPanel();
+    startupTab.setBorder(
+            new TitledBorder(MessageManager.getString("label.memory")));
+    startupTab.setLayout(new GridBagLayout());
+
+    GridBagConstraints gbc = new GridBagConstraints();
+    gbc.weightx = 0.0;
+    gbc.weighty = 0.0;
+    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
+    gbc.fill = GridBagConstraints.NONE;
+
+    initMemoryPanel();
+
+    gbc.gridheight = 1;
+    gbc.gridwidth = 3;
+
+    gbc.gridy = 0; // row 1
+    gbc.gridx = 0;
+    JLabel memoryText = new JLabel();
+    memoryText.setFont(LABEL_FONT_ITALIC);
+    memoryText
+            .setText(MessageManager.getString("label.memory_setting_text"));
+    startupTab.add(memoryText, gbc);
+
+    gbc.gridy++; // row 2
+    gbc.gridx = 0;
+    JPanel exampleMemoryPanel = new JPanel();
+    exampleMemoryPanel
+            .setLayout(new BoxLayout(exampleMemoryPanel, BoxLayout.Y_AXIS));
+    exampleMemoryPanel.setToolTipText(JvSwingUtils.wrapTooltip(true,
+            MessageManager.getString("label.memory_example_tooltip")));
+    JLabel exampleTextLabel = new JLabel();
+    exampleTextLabel
+            .setText(MessageManager.getString("label.memory_example_text"));
+    exampleTextLabel.setForeground(Color.GRAY);
+    exampleTextLabel.setFont(LABEL_FONT);
+    exampleMemoryPanel.add(exampleTextLabel);
+    exampleMemoryPanel.add(exampleMemoryLabel);
+    exampleMemoryPanel.setBackground(Color.WHITE);
+    exampleMemoryPanel.setBorder(BorderFactory.createEtchedBorder());
+    startupTab.add(exampleMemoryPanel, gbc);
+
+    gbc.gridy++; // row 3
+    gbc.gridx = 0;
+    startupTab.add(customiseMemorySetting, gbc);
+
+    gbc.gridy += 2; // row 4 with a gap
+    gbc.gridx = 0;
+    startupTab.add(maxMemoryLabel, gbc);
+
+    gbc.gridy += 2; // row 5
+    gbc.gridx = 0;
+    gbc.gridwidth = 1;
+    startupTab.add(jvmMemoryPercentLabel, gbc);
+    gbc.gridx++;
+    startupTab.add(jvmMemoryPercentSlider, gbc);
+    gbc.gridx++;
+    // gbc.weightx = 0.1;
+    startupTab.add(jvmMemoryPercentDisplay, gbc);
+    // gbc.weightx = 1.0;
+    gbc.gridwidth = 3;
+
+    gbc.gridy++; // row 6
+    gbc.gridx = 0;
+    startupTab.add(jvmMemoryMaxLabel, gbc);
+    gbc.gridx++;
+    startupTab.add(jvmMemoryMaxTextField, gbc);
+
+    gbc.gridy++; // row 7
+    gbc.gridx = 0;
+    gbc.gridwidth = 4;
+    exampleMemoryMessageTextArea.setBackground(startupTab.getBackground());
+    JScrollPane sp = new JScrollPane(exampleMemoryMessageTextArea);
+    sp.setBorder(BorderFactory.createEmptyBorder());
+    sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+    sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
+    startupTab.add(sp, gbc);
+
+    // fill empty space to push widget to top left
+    gbc.gridy++;
+    gbc.weighty = 1.0;
+    gbc.gridx = 100;
+    gbc.gridwidth = 1;
+    gbc.weightx = 1.0;
+    startupTab.add(new JPanel(), gbc);
+
+    setMemoryPercentDisplay();
+    memoryOptionsSetEnabled();
+    return startupTab;
+  }
+
+  private void initMemoryPanel()
+  {
+    // Enable memory settings checkbox
+    customiseMemorySetting.setFont(LABEL_FONT_BOLD);
+    customiseMemorySetting.setText(
+            MessageManager.getString("label.customise_memory_settings"));
+    customiseMemorySetting.addActionListener(new ActionListener()
+    {
+      @Override
+      public void actionPerformed(ActionEvent e)
+      {
+        memoryOptionsSetEnabled();
+      }
+    });
+
+    loadLastSavedMemorySettings();
+
+    exampleMemoryLabel.setFont(LABEL_FONT_BOLD);
+    exampleMemoryLabel.setBackground(Color.WHITE);
+
+    maxMemoryLabel = new JLabel(
+            MessageManager.getString("label.maximum_memory_used"));
+    maxMemoryLabel.setFont(LABEL_FONT_BOLD);
+
+    // Maximum memory percentage slider
+    jvmMemoryPercentLabel.setFont(LABEL_FONT);
+    jvmMemoryPercentLabel.setText(
+            MessageManager.getString("label.percent_of_physical_memory"));
+    jvmMemoryPercentSlider.setPaintLabels(true);
+    jvmMemoryPercentSlider.setPaintTicks(true);
+    jvmMemoryPercentSlider.setPaintTrack(true);
+    jvmMemoryPercentSlider.setMajorTickSpacing(50);
+    jvmMemoryPercentSlider.setMinorTickSpacing(10);
+    jvmMemoryPercentSlider.addChangeListener(new ChangeListener()
+    {
+      @Override
+      public void stateChanged(ChangeEvent e)
+      {
+        setMemoryPercentDisplay();
+      }
+    });
+    jvmMemoryPercentDisplay.setFont(LABEL_FONT);
+    setMemoryPercentDisplay();
+
+    // Maximum memory cap textbox
+    jvmMemoryMaxLabel.setFont(LABEL_FONT);
+    jvmMemoryMaxLabel
+            .setText(MessageManager.getString("label.maximum_memory"));
+    initMemoryMaxTextField();
+
+    exampleMemoryMessageTextArea.setFont(LABEL_FONT_ITALIC);
+    exampleMemoryMessageTextArea.setForeground(Color.GRAY);
+    exampleMemoryMessageTextArea.setEditable(false);
+    exampleMemoryMessageTextArea.setLineWrap(true);
+    exampleMemoryMessageTextArea.setWrapStyleWord(true);
+    exampleMemoryMessageTextArea.setText(" ");
+    exampleMemoryMessageTextArea.setRows(2);
+    exampleMemoryMessageTextArea.setColumns(40);
+
+    setExampleMemoryLabel();
+  }
+
+  private void initMemoryMaxTextField()
+  {
+    jvmMemoryMaxTextField.setToolTipText(
+            MessageManager.getString("label.maximum_memory_tooltip"));
+    jvmMemoryMaxTextField.addActionListener(new ActionListener()
+    {
+      @Override
+      public void actionPerformed(ActionEvent arg0)
+      {
+        validateMemoryMaxTextField();
+        setExampleMemoryLabel();
+      }
+    });
+
+    jvmMemoryMaxTextField.addKeyListener(new KeyListener()
+    {
+      @Override
+      public void keyReleased(KeyEvent e)
+      {
+        validateMemoryMaxTextField();
+        setExampleMemoryLabel();
+      }
+
+      @Override
+      public void keyPressed(KeyEvent e)
+      {
+      }
+
+      // try and stop invalid typing
+      @Override
+      public void keyTyped(KeyEvent e)
+      {
+        char c = Character.toLowerCase(e.getKeyChar());
+        String text = jvmMemoryMaxTextField.getText();
+        String suffixes = "tgmkb";
+        int pos = jvmMemoryMaxTextField.getCaretPosition();
+        int suffixPos = StringUtils.firstCharPosIgnoreCase(text, suffixes);
+        if (!((('0' <= c && c <= '9')
+                && (suffixPos == -1 || pos <= suffixPos)) // digits only allowed
+                // before suffix
+                || (suffixes.indexOf(Character.toLowerCase(c)) >= 0 // valid
+                                                                    // suffix
+                        && pos == text.length() // at end of text and
+                        && suffixPos == -1) // there isn't already one
+        ))
+        {
+          // don't process
+          e.consume();
+        }
+      }
+    });
+  }
+
+  private boolean isMemoryMaxTextFieldValid()
+  {
+    return MemorySetting
+            .isValidMemoryString(jvmMemoryMaxTextField.getText());
+  }
+
+  private void validateMemoryMaxTextField()
+  {
+    if (isMemoryMaxTextFieldValid())
+    {
+      jvmMemoryMaxTextField.setBackground(Color.WHITE);
+    }
+    else
+    {
+      jvmMemoryMaxTextField.setBackground(Color.PINK);
+    }
+  }
+
+  private void setMemoryPercentDisplay()
+  {
+    jvmMemoryPercentDisplay
+            .setText(jvmMemoryPercentSlider.getValue() + "%");
+    setExampleMemoryLabel();
+  }
+
+  private void setExampleMemoryLabel()
+  {
+    boolean selected = customiseMemorySetting.isSelected();
+    int jvmmempc = jvmMemoryPercentSlider.getValue();
+    String jvmmemmax = jvmMemoryMaxTextField.getText();
+
+    long mem;
+    if (selected && (0 <= jvmmempc && jvmmempc <= 100)
+            && MemorySetting.isValidMemoryString(jvmmemmax))
+    {
+      mem = MemorySetting.getMemorySetting(jvmmemmax,
+              String.valueOf(jvmmempc), false, true);
+    }
+    else
+    {
+      mem = MemorySetting.getMemorySetting(null, null, false, true);
+    }
+    exampleMemoryLabel.setText(MemorySetting.memoryLongToString(mem));
+    String message = MemorySetting.getAdjustmentMessage();
+    exampleMemoryMessageTextArea.setText(
+            MessageManager.getString("label.adjustments_for_this_computer")
+                    + ": "
+                    + (message == null
+                            ? MessageManager.getString("label.none")
+                            : message));
+  }
+
+  private void memoryOptionsSetEnabled()
+  {
+    boolean enabled = customiseMemorySetting.isSelected();
+    // leave exampleMemoryLabel enabled always
+    maxMemoryLabel.setEnabled(enabled);
+    jvmMemoryPercentLabel.setEnabled(enabled);
+    jvmMemoryPercentSlider.setEnabled(enabled);
+    jvmMemoryPercentDisplay.setEnabled(enabled);
+    jvmMemoryMaxLabel.setEnabled(enabled);
+    jvmMemoryMaxTextField.setEnabled(enabled);
+    exampleMemoryMessageTextArea.setEnabled(enabled);
+    setExampleMemoryLabel();
+  }
+
   /**
    * Initialises the Backups tabbed panel.
    * 
@@ -2470,7 +2794,7 @@ public class GPreferences extends JPanel
     }
     else
     {
-      Cache.log.error(
+      Console.error(
               "Preset '" + value + "' [key:" + key + "] not implemented");
     }
 
@@ -2490,7 +2814,7 @@ public class GPreferences extends JPanel
               .getSelectedItem();
     } catch (Exception ex)
     {
-      Cache.log.error(
+      Console.error(
               "Problem casting Combo entry to IntKeyStringValueEntry.");
       e = null;
     }
@@ -2508,7 +2832,7 @@ public class GPreferences extends JPanel
         e = (IntKeyStringValueEntry) backupfilesPresetsCombo2.getItemAt(i);
       } catch (Exception ex)
       {
-        Cache.log.error(
+        Console.error(
                 "Problem casting Combo entry to IntKeyStringValueEntry. Skipping item. ");
         continue;
       }
@@ -2956,7 +3280,7 @@ public class GPreferences extends JPanel
         i = ((Integer) s.getValue()).intValue();
       } catch (Exception e)
       {
-        Cache.log.error(
+        Console.error(
                 "Exception casting the initial value of s.getValue()");
       }
     }
@@ -2992,7 +3316,7 @@ public class GPreferences extends JPanel
       i = (Integer) s.getValue();
     } catch (Exception e)
     {
-      Cache.log.error("Failed casting (Integer) JSpinner s.getValue()");
+      Console.error("Failed casting (Integer) JSpinner s.getValue()");
     }
     return i;
   }
index 84de493..928b370 100644 (file)
@@ -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 (file)
index 0000000..2f4fafb
--- /dev/null
@@ -0,0 +1,196 @@
+package jalview.log;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import jalview.bin.Console;
+import jalview.util.Platform;
+
+public abstract class JLogger implements JLoggerI
+{
+  protected String name;
+
+  protected LogLevel level;
+
+  private Object logger = null;
+
+  private static Map<String, JLogger> 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)
+    {
+      Console.error("Could not parse LogLevel '" + levelString + "'", e);
+      return LogLevel.INFO;
+    }
+  }
+
+  public static JLogger getLogger(Class c)
+  {
+    return getLogger(c);
+  }
+
+  public static JLogger getLogger(Class c, LogLevel loglevel)
+  {
+    return getLogger(c.getCanonicalName(), loglevel);
+  }
+
+  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 loglevel, String message, Throwable t)
+  {
+    if (loglevel.compareTo(this.level) < 0)
+    {
+      return false;
+    }
+    if (!loggerExists() || Platform.isJS())
+    {
+      String logLine = String.format("%s: %s", loglevel.toString(),
+              message);
+      System.out.println(logLine);
+      if (t != null)
+      {
+        if (loglevel.compareTo(LogLevel.DEBUG) <= 0)
+          t.printStackTrace(System.err);
+        else
+          System.err.println(t.getMessage());
+      }
+      return false;
+    }
+    else
+    {
+      loggerLogMessage(loglevel, 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 (file)
index 0000000..94f149b
--- /dev/null
@@ -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 (file)
index 0000000..bacab74
--- /dev/null
@@ -0,0 +1,146 @@
+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(Class c)
+  {
+    return getLogger(c);
+  }
+
+  public static JLoggerLog4j getLogger(Class c, LogLevel loglevel)
+  {
+    return getLogger(c.getCanonicalName(), loglevel);
+  }
+
+  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)
+  {
+    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 level,
+          Appender appender)
+  {
+    if (!Platform.isJS())
+      Log4j.addAppender(level.getLoggerObject(), appender);
+  }
+
+  public synchronized static void addAppender(JLoggerLog4j l1,
+          JLoggerLog4j l2, String name)
+  {
+    if (!Platform.isJS())
+      Log4j.addAppender(l1.getLoggerObject(), l2.getLoggerObject(), name);
+  }
+
+}
similarity index 56%
rename from src/jalview/gui/JalviewAppender.java
rename to src/jalview/log/JalviewAppender.java
index 1d7064b..07239f8 100644 (file)
  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
  * The Jalview Authors are detailed in the 'AUTHORS' file.
  */
-package jalview.gui;
+package jalview.log;
+
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
 
 import javax.swing.JTextArea;
 import javax.swing.SwingUtilities;
 
-import org.apache.log4j.WriterAppender;
-import org.apache.log4j.spi.LoggingEvent;
+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.config.Property;
+
+import jalview.log.JLoggerI.LogLevel;
+import jalview.util.Log4j;
 
 /**
  * From http://textareaappender.zcage.com/ the means to capture the logs, too.
  * Simple example of creating a Log4j appender that will write to a JTextArea.
  */
-public class JalviewAppender extends WriterAppender
+public class JalviewAppender extends AbstractAppender
 {
+  public final static String NAME = "JalviewAppender";
+
+  public JalviewAppender()
+  {
+    this(LogLevel.INFO);
+  }
+
+  public JalviewAppender(LogLevel loglevel)
+  {
+    super(NAME,
+            Log4j.getThresholdFilter(loglevel == null ? Level.INFO
+                    : Log4j.log4jLevel(loglevel)),
+            Log4j.getSimpleLayout(), false, new Property[0]);
+  }
+
+  protected JalviewAppender(String name, Filter filter,
+          Layout<? extends Serializable> layout, boolean ignoreExceptions,
+          Property[] properties)
+  {
+    super(name, filter, layout, ignoreExceptions, properties);
+    // TODO Auto-generated constructor stub
+  }
 
   static private JTextArea jTextArea = null;
 
@@ -44,9 +76,10 @@ public class JalviewAppender extends WriterAppender
   /**
    * Format and then append the loggingEvent to the stored JTextArea.
    */
-  public void append(LoggingEvent loggingEvent)
+  public void append(LogEvent logEvent)
   {
-    final String message = this.layout.format(loggingEvent);
+    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()
index acfeb2a..8877af2 100644 (file)
@@ -84,6 +84,7 @@ import jalview.api.analysis.ScoreModelI;
 import jalview.api.analysis.SimilarityParamsI;
 import jalview.api.structures.JalviewStructureDisplayI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentAnnotation;
@@ -576,7 +577,7 @@ public class Jalview2XML
 
     } catch (Exception e)
     {
-      Cache.log.error("Couln't write Jalview state to " + statefile, e);
+      Console.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 +883,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 +1110,7 @@ public class Jalview2XML
                 }
                 else
                 {
-                  Cache.log.error(
+                  Console.error(
                           "Failed to save viewer state for " + viewerType);
                 }
               }
@@ -1632,7 +1633,7 @@ public class Jalview2XML
                 .getHiddenColumns();
         if (hidden == null)
         {
-          warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
+          Console.warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
         }
         else
         {
@@ -1801,7 +1802,7 @@ public class Jalview2XML
       object.getPcaViewer().add(viewer);
     } catch (Throwable t)
     {
-      Cache.log.error("Error saving PCA: " + t.getMessage());
+      Console.error("Error saving PCA: " + t.getMessage());
     }
   }
 
@@ -2091,7 +2092,7 @@ public class Jalview2XML
       }
       else if (!matchedFile.equals(pdbentry.getFile()))
       {
-        Cache.log.warn(
+        Console.warn(
                 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
                         + pdbentry.getFile());
       }
@@ -2389,7 +2390,7 @@ public class Jalview2XML
                   calcIdParam.getParameters().replace("|\\n|", "\n"));
         } catch (IOException x)
         {
-          warn("Couldn't parse parameter data for "
+          Console.warn("Couldn't parse parameter data for "
                   + calcIdParam.getCalcId(), x);
           return false;
         }
@@ -2417,7 +2418,7 @@ public class Jalview2XML
       }
       else
       {
-        warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
+        Console.warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
         return false;
       }
     }
@@ -2461,7 +2462,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);
+      Console.warn("Cannot find ID for object in external mapping : " + jvobj);
     }
     return altCode;
   }
@@ -2598,12 +2599,12 @@ public class Jalview2XML
         mp.setDseqFor(jmpid);
         if (!seqRefIds.containsKey(jmpid))
         {
-          jalview.bin.Cache.log.debug("creatign new DseqFor ID");
+          Console.debug("creatign new DseqFor ID");
           seqRefIds.put(jmpid, ps);
         }
         else
         {
-          jalview.bin.Cache.log.debug("reusing DseqFor ID");
+          Console.debug("reusing DseqFor ID");
         }
 
         // mp.setMappingChoice(mpc);
@@ -3229,7 +3230,7 @@ public class Jalview2XML
       }
       else
       {
-        warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
+        Console.warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
       }
     } catch (Exception ex)
     {
@@ -4204,7 +4205,7 @@ public class Jalview2XML
         tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
         if (tp == null)
         {
-          warn("There was a problem recovering stored Newick tree: \n"
+          Console.warn("There was a problem recovering stored Newick tree: \n"
                   + tree.getNewick());
           continue;
         }
@@ -4366,7 +4367,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);
+              Console.warn(errorMessage);
             }
           }
         }
@@ -4421,7 +4422,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);
+      Console.error("Invalid structure viewer type: " + type);
     }
   }
 
@@ -4953,7 +4954,7 @@ public class Jalview2XML
           }
           else
           {
-            warn("Couldn't recover parameters for "
+            Console.warn("Couldn't recover parameters for "
                     + calcIdParam.getCalcId());
           }
         }
@@ -5229,10 +5230,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);
-      }
+      Console.debug("Skipping seuqence set id " + id);
       return true;
     }
     return false;
@@ -5284,14 +5282,14 @@ public class Jalview2XML
       {
         if (ds != null && ds != seqSetDS)
         {
-          warn("JAL-3171 regression: Overwriting a dataset reference for an alignment"
+          Console.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.");
+            Console.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 +5314,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()
+      Console.debug("Created new dataset " + vamsasSet.getDatasetId()
               + " for alignment " + System.identityHashCode(al));
       addDatasetRef(vamsasSet.getDatasetId(), ds);
     }
@@ -5369,7 +5367,7 @@ public class Jalview2XML
       AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds);
       if (prevDS != null && prevDS != ds)
       {
-        warn("Dataset sequence appears in many datasets: "
+        Console.warn("Dataset sequence appears in many datasets: "
                 + restoredSeq.getDsseqid());
         // TODO: try to merge!
       }
@@ -5575,7 +5573,7 @@ public class Jalview2XML
   {
     if (dataset.getDataset() != null)
     {
-      warn("Serious issue!  Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
+      Console.warn("Serious issue!  Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
     }
     String datasetId = makeHashCode(dataset, null);
     if (datasetId == null)
@@ -5711,7 +5709,7 @@ public class Jalview2XML
         seqRefIds.put(sqid, djs);
 
       }
-      jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
+      Console.debug("about to recurse on addDBRefs.");
       addDBRefs(djs, ms);
 
     }
@@ -5764,62 +5762,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 +5820,7 @@ public class Jalview2XML
         if (!jvann.annotationId.equals(anid))
         {
           // TODO verify that this is the correct behaviour
-          this.warn("Overriding Annotation ID for " + anid
+          Console.warn("Overriding Annotation ID for " + anid
                   + " from different id : " + jvann.annotationId);
           jvann.annotationId = anid;
         }
@@ -5893,7 +5835,7 @@ public class Jalview2XML
       }
       else
       {
-        Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
+        Console.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
       }
     }
   }
@@ -5963,7 +5905,7 @@ public class Jalview2XML
       }
       else
       {
-        warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
+        Console.warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
       }
     } catch (Exception ex)
     {
@@ -6113,7 +6055,7 @@ public class Jalview2XML
       }
     } catch (Exception ex)
     {
-      Cache.log.error("Error loading PCA: " + ex.toString());
+      Console.error("Error loading PCA: " + ex.toString());
     }
   }
 
@@ -6173,7 +6115,7 @@ public class Jalview2XML
       });
     } catch (InvocationTargetException | InterruptedException ex)
     {
-      warn("Unexpected error when opening " + viewerType
+      Console.warn("Unexpected error when opening " + viewerType
               + " structure viewer", ex);
     }
   }
@@ -6280,7 +6222,7 @@ public class Jalview2XML
       }
     } catch (IOException e)
     {
-      Cache.log.error("Error restoring Jmol session: " + e.toString());
+      Console.error("Error restoring Jmol session: " + e.toString());
     }
     return null;
   }
@@ -6533,7 +6475,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);
+        Console.warn("Couldn't parse out graduated feature color.", e);
       }
 
       NoValueColour noCol = colourModel.getNoValueColour();
index b4bd781..0209e20 100644 (file)
@@ -34,7 +34,7 @@ import java.util.Vector;
 
 import jalview.analysis.AlignSeq;
 import jalview.api.StructureSelectionManagerProvider;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.commands.CommandI;
 import jalview.commands.EditCommand;
 import jalview.commands.OrderCommand;
@@ -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");
+      Console.error("SIFTS mapping failed", e);
+      Console.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());
+            Console.error(e.getMessage());
             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
                     targetChainId, maxChain, pdb, maxAlignseq);
             seqToStrucMapping.add(nwMapping);
index f1f2d30..3414e95 100644 (file)
@@ -41,7 +41,7 @@ import jalview.api.FeatureRenderer;
 import jalview.api.SequenceRenderer;
 import jalview.api.StructureSelectionManagerProvider;
 import jalview.api.structures.JalviewStructureDisplayI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.HiddenColumns;
 import jalview.datamodel.MappedFeatures;
@@ -1497,7 +1497,7 @@ public abstract class AAStructureBindingModel
       saveSession(f);
     } catch (IOException e)
     {
-      Cache.log.error(String.format("Error saving %s session: %s", prefix,
+      Console.error(String.format("Error saving %s session: %s", prefix,
               e.toString()));
     }
 
index a0f42f0..02e565e 100644 (file)
@@ -21,7 +21,7 @@
 
 package jalview.urls;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.urls.api.UrlProviderI;
 import jalview.util.UrlLink;
 
@@ -101,7 +101,7 @@ public class UrlLinkTableModel extends AbstractTableModel
           dataProvider.setUrlData(data);
         } catch (IllegalArgumentException ex)
         {
-          Cache.log.error(ex.getMessage());
+          Console.error(ex.getMessage());
         }
       }
     });
index 8119daa..dbd9177 100755 (executable)
@@ -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;
     }
index 109eaa5..40f6110 100644 (file)
@@ -1,6 +1,9 @@
 package jalview.util;
 
 import java.awt.Image;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
@@ -13,14 +16,12 @@ import java.util.Properties;
 
 import javax.swing.ImageIcon;
 
-import jalview.bin.Cache;
-
 public class ChannelProperties
 {
 
-  private static final String CHANNEL_PROPERTIES_FILENAME = "/channel.props";
+  public static final String CHANNEL_PROPERTIES_FILENAME = "channel.props";
 
-  private static final Properties channelProps;
+  private static Properties channelProps;
 
   private static final Properties defaultProps;
 
@@ -60,11 +61,11 @@ public class ChannelProperties
     // load channel_properties
     Properties tryChannelProps = new Properties();
     URL channelPropsURL = ChannelProperties.class
-            .getResource(CHANNEL_PROPERTIES_FILENAME);
+            .getResource("/" + CHANNEL_PROPERTIES_FILENAME);
     if (channelPropsURL == null)
     {
       // complete failure of channel_properties, set all properties to defaults
-      System.err.println("Failed to find '" + CHANNEL_PROPERTIES_FILENAME
+      System.err.println("Failed to find '/" + CHANNEL_PROPERTIES_FILENAME
               + "' file at '"
               + (channelPropsURL == null ? "null"
                       : channelPropsURL.toString())
@@ -80,7 +81,7 @@ public class ChannelProperties
         channelPropsIS.close();
       } catch (IOException e)
       {
-        Cache.log.warn(e.getMessage());
+        System.err.println(e.getMessage());
         // return false;
       }
     }
@@ -113,7 +114,9 @@ public class ChannelProperties
         Image logo = null;
         String path = defaultProps.getProperty("logo." + size);
         URL imageURL = ChannelProperties.class.getResource(path);
-        logo = new ImageIcon(imageURL).getImage();
+        ImageIcon imgIcon = imageURL == null ? null
+                : new ImageIcon(imageURL);
+        logo = imgIcon == null ? null : imgIcon.getImage();
         if (logo != null)
         {
           iconList.add(logo);
@@ -122,6 +125,25 @@ public class ChannelProperties
     }
   }
 
+  protected static void loadProps(File dir)
+  {
+    File channelPropsFile = new File(dir, CHANNEL_PROPERTIES_FILENAME);
+    if (channelPropsFile.exists())
+    {
+      try
+      {
+        InputStream is = new FileInputStream(channelPropsFile);
+        channelProps.load(is);
+      } catch (FileNotFoundException e)
+      {
+        System.err.println(e.getMessage());
+      } catch (IOException e)
+      {
+        System.err.println(e.getMessage());
+      }
+    }
+  }
+
   private static Properties channelProps()
   {
     return channelProps;
@@ -219,7 +241,8 @@ public class ChannelProperties
       }
 
       URL imageURL = ChannelProperties.class.getResource(path);
-      img = new ImageIcon(imageURL).getImage();
+      ImageIcon imgIcon = imageURL == null ? null : new ImageIcon(imageURL);
+      img = imgIcon == null ? null : imgIcon.getImage();
       if (img == null)
       {
         System.err.println(
diff --git a/src/jalview/util/LaunchUtils.java b/src/jalview/util/LaunchUtils.java
new file mode 100644 (file)
index 0000000..3302dba
--- /dev/null
@@ -0,0 +1,56 @@
+package jalview.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Properties;
+
+public class LaunchUtils
+{
+
+  public static void loadChannelProps(File dir)
+  {
+    ChannelProperties.loadProps(dir);
+  }
+
+  private static Properties userPreferences = null;
+
+  public static String getUserPreference(String key)
+  {
+    if (userPreferences == null)
+    {
+      String channelPrefsFilename = ChannelProperties
+              .getProperty("preferences.filename");
+      if (channelPrefsFilename == null)
+      {
+        return null;
+      }
+      File propertiesFile = new File(System.getProperty("user.home"),
+              channelPrefsFilename);
+      if (!propertiesFile.exists())
+      {
+        return null;
+      }
+      try
+      {
+        userPreferences = new Properties();
+        userPreferences.load(new FileInputStream(propertiesFile));
+      } catch (FileNotFoundException e)
+      {
+        // didn't find user preferences file
+        return null;
+      } catch (IOException e)
+      {
+        System.err.println(e.getMessage());
+        return null;
+      }
+    }
+    return userPreferences.getProperty(key);
+  }
+
+  public static boolean getBooleanUserPreference(String key)
+  {
+    return Boolean.parseBoolean(getUserPreference(key));
+  }
+}
diff --git a/src/jalview/util/Log4j.java b/src/jalview/util/Log4j.java
new file mode 100644 (file)
index 0000000..05c641b
--- /dev/null
@@ -0,0 +1,204 @@
+package jalview.util;
+
+import java.util.Map;
+
+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<BuiltConfiguration> 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<BuiltConfiguration> 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)
+  {
+    if (!Platform.isJS())
+    {
+      LoggerContext context = (LoggerContext) LogManager.getContext(false);
+      Configuration config = context.getConfiguration();
+      LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
+      loggerConfig.setLevel(level);
+
+      Map<String, Appender> 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)
+  {
+    setLevel(LogManager.getRootLogger(), level);
+  }
+
+  public static Appender getAppender(String name)
+  {
+    LoggerContext context = (LoggerContext) LogManager.getContext(false);
+    Configuration config = context.getConfiguration();
+    Map<String, Appender> appenders = config.getAppenders();
+    return appenders.get(name);
+  }
+
+  public static void addAppender(Logger logger, Logger logger2,
+          String name2)
+  {
+    LoggerContext context = (LoggerContext) LogManager.getContext(false);
+    Configuration config = context.getConfiguration();
+    LoggerConfig logger2Config = config.getLoggerConfig(logger2.getName());
+    Map<String, Appender> logger2AppendersMap = logger2Config
+            .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)
+  {
+    Log4j.addAppender(LogManager.getRootLogger(), appender);
+  }
+}
index 3555e52..d6a125b 100644 (file)
@@ -25,6 +25,8 @@ import java.util.Arrays;
 import java.util.BitSet;
 import java.util.List;
 
+import jalview.bin.Console;
+
 /**
  * A simple way of bijectively mapping a non-contiguous linear range to another
  * non-contiguous linear range.
@@ -307,7 +309,7 @@ public class MapList
       if (range.length != 2)
       {
         // throw new IllegalArgumentException(range);
-        System.err.println("Invalid format for fromRange "
+        Console.error("Invalid format for fromRange "
                 + Arrays.toString(range) + " may cause errors");
       }
       fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
@@ -321,7 +323,7 @@ public class MapList
       if (range.length != 2)
       {
         // throw new IllegalArgumentException(range);
-        System.err.println("Invalid format for toRange "
+        Console.error("Invalid format for toRange "
                 + Arrays.toString(range) + " may cause errors");
       }
       toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
@@ -467,7 +469,8 @@ public class MapList
     int mp[][] = new int[to - from + 2][];
     for (int i = 0; i < mp.length; i++)
     {
-      int[] m = shift(i + from, shiftTo, sourceRatio, shiftFrom, targetRatio);
+      int[] m = shift(i + from, shiftTo, sourceRatio, shiftFrom,
+              targetRatio);
       if (m != null)
       {
         if (i == 0)
@@ -1144,10 +1147,11 @@ public class MapList
   }
 
   /**
-   * Returns the [start1, end1, start2, end2, ...] positions in the 'from' range
-   * that map to positions between {@code start} and {@code end} in the 'to'
-   * range. Note that for a reverse strand mapping this will return ranges with
-   * end < start. Returns null if no mapped positions are found in start-end.
+   * <<<<<<< HEAD Returns the [start1, end1, start2, end2, ...] positions in the
+   * 'from' range that map to positions between {@code start} and {@code end} in
+   * the 'to' range. Note that for a reverse strand mapping this will return
+   * ranges with end < start. Returns null if no mapped positions are found in
+   * start-end.
    * 
    * @param start
    * @param end
@@ -1155,8 +1159,8 @@ public class MapList
    */
   public int[] locateInFrom(int start, int end)
   {
-    return mapPositions(start, end, toShifts, fromShifts,
-            toRatio, fromRatio);
+    return mapPositions(start, end, toShifts, fromShifts, toRatio,
+            fromRatio);
   }
 
   /**
@@ -1171,8 +1175,8 @@ public class MapList
    */
   public int[] locateInTo(int start, int end)
   {
-    return mapPositions(start, end, fromShifts, toShifts,
-            fromRatio, toRatio);
+    return mapPositions(start, end, fromShifts, toShifts, fromRatio,
+            toRatio);
   }
 
   /**
@@ -1250,7 +1254,8 @@ public class MapList
    * @return
    */
   protected final static BitSet getMappedOffsetsForPositions(int start,
-          int end, List<int[]> sourceRange, int sourceWordLength, int targetWordLength)
+          int end, List<int[]> sourceRange, int sourceWordLength,
+          int targetWordLength)
   {
     BitSet overlaps = new BitSet();
     int offset = 0;
@@ -1419,4 +1424,36 @@ public class MapList
 
     return added;
   }
+
+  /*
+   * Returns the [start, end...] positions in the range mapped from, that are
+   * mapped to by part or all of the given begin-end of the range mapped to.
+   * Returns null if begin-end does not overlap any position mapped to.
+   * 
+   * @param begin
+   * @param end
+   * @return
+   */
+  public int[] getOverlapsInFrom(final int begin, final int end)
+  {
+    int[] overlaps = MappingUtils.findOverlap(toShifts, begin, end);
+
+    return overlaps == null ? null : locateInFrom(overlaps[0], overlaps[1]);
+  }
+
+  /**
+   * Returns the [start, end...] positions in the range mapped to, that are
+   * mapped to by part or all of the given begin-end of the range mapped from.
+   * Returns null if begin-end does not overlap any position mapped from.
+   * 
+   * @param begin
+   * @param end
+   * @return
+   */
+  public int[] getOverlapsInTo(final int begin, final int end)
+  {
+    int[] overlaps = MappingUtils.findOverlap(fromShifts, begin, end);
+
+    return overlaps == null ? null : locateInTo(overlaps[0], overlaps[1]);
+  }
 }
index c8b5190..8d34ea8 100644 (file)
@@ -29,7 +29,7 @@ import java.util.Map;
 
 import jalview.analysis.AlignmentSorter;
 import jalview.api.AlignViewportI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.commands.CommandI;
 import jalview.commands.EditCommand;
 import jalview.commands.EditCommand.Action;
@@ -41,6 +41,7 @@ import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentOrder;
 import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.HiddenColumns;
+import jalview.datamodel.Mapping;
 import jalview.datamodel.SearchResultMatchI;
 import jalview.datamodel.SearchResults;
 import jalview.datamodel.SearchResultsI;
@@ -80,7 +81,7 @@ public final class MappingUtils
       action = action.getUndoAction();
     }
     // TODO write this
-    Cache.log.error("MappingUtils.mapCutOrPaste not yet implemented");
+    Console.error("MappingUtils.mapCutOrPaste not yet implemented");
   }
 
   /**
@@ -363,49 +364,55 @@ public final class MappingUtils
        */
       int startResiduePos = selected.findPosition(firstUngappedPos);
       int endResiduePos = selected.findPosition(lastUngappedPos);
-
-      for (AlignedCodonFrame acf : codonFrames)
+      for (SequenceI seq : mapTo.getAlignment().getSequences())
       {
-        for (SequenceI seq : mapTo.getAlignment().getSequences())
+        int mappedStartResidue = 0;
+        int mappedEndResidue = 0;
+        for (AlignedCodonFrame acf : codonFrames)
         {
-          SequenceI peptide = targetIsNucleotide ? selected : seq;
-          SequenceI cds = targetIsNucleotide ? seq : selected;
-          SequenceToSequenceMapping s2s = acf.getCoveringMapping(cds,
-                  peptide);
-          if (s2s == null)
-          {
-            continue;
-          }
-          int mappedStartResidue = 0;
-          int mappedEndResidue = 0;
-          List<AlignedCodonFrame> mapping = Arrays.asList(acf);
-          SearchResultsI sr = buildSearchResults(selected, startResiduePos,
-                  mapping);
-          for (SearchResultMatchI m : sr.getResults())
+          // rather than use acf.getCoveringMapping() we iterate through all
+          // mappings to make sure all CDS are selected for a protein
+          for (SequenceToSequenceMapping map: acf.getMappings())
           {
-            mappedStartResidue = m.getStart();
-            mappedEndResidue = m.getEnd();
-          }
-          sr = buildSearchResults(selected, endResiduePos, mapping);
-          for (SearchResultMatchI m : sr.getResults())
+          if (map.covers(selected) && map.covers(seq))
           {
-            mappedStartResidue = Math.min(mappedStartResidue, m.getStart());
-            mappedEndResidue = Math.max(mappedEndResidue, m.getEnd());
-          }
+            /*
+             * Found a sequence mapping. Locate the start/end mapped residues.
+             */
+            List<AlignedCodonFrame> mapping = Arrays
+                    .asList(new AlignedCodonFrame[]
+                    { acf });
+            // locate start 
+            SearchResultsI sr = buildSearchResults(selected,
+                    startResiduePos, mapping);
+            for (SearchResultMatchI m : sr.getResults())
+            {
+              mappedStartResidue = m.getStart();
+              mappedEndResidue = m.getEnd();
+            }
+            // locate end - allowing for adjustment of start range
+            sr = buildSearchResults(selected, endResiduePos, mapping);
+            for (SearchResultMatchI m : sr.getResults())
+            {
+              mappedStartResidue = Math.min(mappedStartResidue,
+                      m.getStart());
+              mappedEndResidue = Math.max(mappedEndResidue, m.getEnd());
+            }
 
-          /*
-           * Find the mapped aligned columns, save the range. Note findIndex
-           * returns a base 1 position, SequenceGroup uses base 0
-           */
-          int mappedStartCol = seq.findIndex(mappedStartResidue) - 1;
-          minStartCol = minStartCol == -1 ? mappedStartCol
-                  : Math.min(minStartCol, mappedStartCol);
-          int mappedEndCol = seq.findIndex(mappedEndResidue) - 1;
-          maxEndCol = maxEndCol == -1 ? mappedEndCol
-                  : Math.max(maxEndCol, mappedEndCol);
-          mappedGroup.addSequence(seq, false);
-          break;
-        }
+            /*
+             * Find the mapped aligned columns, save the range. Note findIndex
+             * returns a base 1 position, SequenceGroup uses base 0
+             */
+            int mappedStartCol = seq.findIndex(mappedStartResidue) - 1;
+            minStartCol = minStartCol == -1 ? mappedStartCol
+                    : Math.min(minStartCol, mappedStartCol);
+            int mappedEndCol = seq.findIndex(mappedEndResidue) - 1;
+            maxEndCol = maxEndCol == -1 ? mappedEndCol
+                    : Math.max(maxEndCol, mappedEndCol);
+            mappedGroup.addSequence(seq, false);
+            break;
+          }
+        }}
       }
     }
     mappedGroup.setStartRes(minStartCol < 0 ? 0 : minStartCol);
@@ -835,7 +842,7 @@ public final class MappingUtils
     {
       if (range.length % 2 != 0)
       {
-        System.err.println(
+        Console.error(
                 "Error unbalance start/end ranges: " + ranges.toString());
         return 0;
       }
@@ -991,7 +998,7 @@ public final class MappingUtils
         /*
          * not coded for [start1, end1, start2, end2, ...]
          */
-        System.err.println(
+        Console.error(
                 "MappingUtils.removeEndPositions doesn't handle multiple  ranges");
         return;
       }
@@ -1002,7 +1009,7 @@ public final class MappingUtils
         /*
          * not coded for a reverse strand range (end < start)
          */
-        System.err.println(
+        Console.error(
                 "MappingUtils.removeEndPositions doesn't handle reverse strand");
         return;
       }
@@ -1039,4 +1046,66 @@ public final class MappingUtils
     }
     return result;
   }
+
+  /*
+   * Returns the maximal start-end positions in the given (ordered) list of
+   * ranges which is overlapped by the given begin-end range, or null if there
+   * is no overlap.
+   * 
+   * <pre>
+   * Examples:
+   *   if ranges is {[4, 8], [10, 12], [16, 19]}
+   * then
+   *   findOverlap(ranges, 1, 20) == [4, 19]
+   *   findOverlap(ranges, 6, 11) == [6, 11]
+   *   findOverlap(ranges, 9, 15) == [10, 12]
+   *   findOverlap(ranges, 13, 15) == null
+   * </pre>
+   * 
+   * @param ranges
+   * @param begin
+   * @param end
+   * @return
+   */
+  protected static int[] findOverlap(List<int[]> ranges, final int begin,
+          final int end)
+  {
+    boolean foundStart = false;
+    int from = 0;
+    int to = 0;
+
+    /*
+     * traverse the ranges to find the first position (if any) >= begin,
+     * and the last position (if any) <= end
+     */
+    for (int[] range : ranges)
+    {
+      if (!foundStart)
+      {
+        if (range[0] >= begin)
+        {
+          /*
+           * first range that starts with, or follows, begin
+           */
+          foundStart = true;
+          from = Math.max(range[0], begin);
+        }
+        else if (range[1] >= begin)
+        {
+          /*
+           * first range that contains begin
+           */
+          foundStart = true;
+          from = begin;
+        }
+      }
+
+      if (range[0] <= end)
+      {
+        to = Math.min(end, range[1]);
+      }
+    }
+
+    return foundStart && to >= from ? new int[] { from, to } : null;
+  }
 }
index ba7da10..acd4591 100644 (file)
@@ -27,7 +27,7 @@ import java.util.ResourceBundle;
 import java.util.ResourceBundle.Control;
 import java.util.Set;
 
-import org.apache.log4j.Logger;
+import jalview.log.JLoggerLog4j;
 
 /**
  * 
@@ -40,8 +40,7 @@ public class MessageManager
 {
   private static ResourceBundle rb;
 
-  // BH 2018 switched to org.apache.llog4j.Logger
-  private static Logger log = Logger
+  private static JLoggerLog4j log = JLoggerLog4j
           .getLogger(MessageManager.class.getCanonicalName());
 
   private static Locale loc;
@@ -94,7 +93,7 @@ public class MessageManager
     } catch (Exception e)
     {
       String msg = "I18N missing: " + loc + "\t" + key;
-         logWarning(key, msg);
+      logWarning(key, msg);
     }
     return value;
   }
@@ -162,15 +161,16 @@ public class MessageManager
    */
   public static String getStringOrReturn(String keyroot, String name)
   {
-    String smkey = keyroot + name.toLowerCase(Locale.ROOT).replaceAll(" ", "");
+    String smkey = keyroot
+            + name.toLowerCase(Locale.ROOT).replaceAll(" ", "");
     try
     {
       name = rb.getString(smkey);
     } catch (Exception x)
     {
-      String msg = "I18N missing key with root " + keyroot + ": " + loc + "\t"
-                         + smkey;
-         logWarning(smkey, msg);
+      String msg = "I18N missing key with root " + keyroot + ": " + loc
+              + "\t" + smkey;
+      logWarning(smkey, msg);
     }
     return name;
   }
@@ -181,12 +181,12 @@ public class MessageManager
    * @param key
    * @param msg
    */
-  private static void logWarning(String key, String msg) 
+  private static void logWarning(String key, String msg)
   {
-       if (!reportedMissing.contains(key))
-       {
+    if (!reportedMissing.contains(key))
+    {
       reportedMissing.add(key);
-         log.info(msg);
-       }
+      log.info(msg);
+    }
   }
 }
index bf5b87a..273f6ec 100644 (file)
@@ -448,7 +448,7 @@ public class StringUtils
     {
       text = text.substring(0, endTag);
     }
-  
+
     if (startTag == -1 && (text.contains("<") || text.contains(">")))
     {
       text = text.replaceAll("<", "&lt;");
@@ -458,8 +458,8 @@ public class StringUtils
   }
 
   /**
-   * Answers the input string with any occurrences of the 'encodeable' characters
-   * replaced by their URL encoding
+   * Answers the input string with any occurrences of the 'encodeable'
+   * characters replaced by their URL encoding
    * 
    * @param s
    * @param encodable
@@ -570,4 +570,18 @@ public class StringUtils
     }
     return enc;
   }
+
+  public static int firstCharPosIgnoreCase(String text, String chars)
+  {
+    int min = text.length() + 1;
+    for (char c : chars.toLowerCase().toCharArray())
+    {
+      int i = text.toLowerCase().indexOf(c);
+      if (0 <= i && i < min)
+      {
+        min = i;
+      }
+    }
+    return min < text.length() + 1 ? min : -1;
+  }
 }
index 80918f9..b64a526 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.ws;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignedCodonFrame;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
@@ -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 "
+            Console.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
+            Console.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.");
+              Console.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);
+              Console.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
+            Console.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.",
+          Console.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(
+      Console.debug(
               "WebServiceJob poll loop finished with no jobs created.");
       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
       wsInfo.appendProgressText(
index 67b44d7..4705fe5 100644 (file)
@@ -37,6 +37,7 @@ import java.util.regex.Pattern;
 import jalview.analysis.AlignSeq;
 import jalview.api.FeatureSettingsModelI;
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.DBRefSource;
@@ -362,9 +363,9 @@ public class DBRefFetcher implements Runnable
           AlignmentI retrieved = null;
           try
           {
-            if (Cache.log.isDebugEnabled())
+            if (Console.isDebugEnabled())
             {
-              Cache.log.debug("Querying " + dbsource.getDbName()
+              Console.debug("Querying " + dbsource.getDbName()
                       + " with : '" + queryString.toString() + "'");
             }
             retrieved = dbsource.getSequenceRecords(queryString.toString());
index 2058800..7cb8f09 100644 (file)
@@ -7,7 +7,7 @@ import java.io.IOException;
 
 import com.stevesoft.pat.Regex;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.SequenceI;
@@ -105,7 +105,7 @@ public abstract class EmblFlatfileSource extends EbiFileRetrievedProxy
 
       if (al == null)
       {
-        Cache.log.error(
+        Console.error(
                 "No record found for '" + dbName + ":" + query + "'");
       }
     }
index c2d661b..034ea4f 100644 (file)
@@ -20,8 +20,6 @@
  */
 package jalview.ws.dbsources;
 
-import java.util.Locale;
-
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStream;
@@ -30,6 +28,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Hashtable;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Map.Entry;
 
@@ -44,7 +43,7 @@ import javax.xml.stream.XMLStreamReader;
 import com.stevesoft.pat.Regex;
 
 import jalview.analysis.SequenceIdMatcher;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
@@ -65,12 +64,6 @@ import jalview.xml.binding.embl.EntryType.Feature.Qualifier;
 import jalview.xml.binding.embl.ROOT;
 import jalview.xml.binding.embl.XrefType;
 
-/**
- * Provides XML binding and parsing of EMBL or EMBLCDS records retrieved from
- * (e.g.) {@code https://www.ebi.ac.uk/ena/data/view/x53828&display=xml}.
- * 
- * @deprecated endpoint withdrawn August 2020 (JAL-3692), use EmblFlatfileSource
- */
 public abstract class EmblXmlSource extends EbiFileRetrievedProxy
 {
   private static final Regex ACCESSION_REGEX = new Regex("^[A-Z]+[0-9]+");
@@ -104,8 +97,8 @@ public abstract class EmblXmlSource extends EbiFileRetrievedProxy
     try
     {
       reply = dbFetch.fetchDataAsFile(
-              emprefx.toLowerCase(Locale.ROOT) + ":" + query.trim(), "display=xml",
-              "xml");
+              emprefx.toLowerCase(Locale.ROOT) + ":" + query.trim(),
+              "display=xml", "xml");
     } catch (Exception e)
     {
       stopQuery();
@@ -455,9 +448,8 @@ public abstract class EmblXmlSource extends EbiFileRetrievedProxy
         else
         {
           // final product length truncation check
-          int[] cdsRanges = adjustForProteinLength(translationLength,
-                  exons);
-          dnaToProteinMapping = new Mapping(product, cdsRanges,
+          int[] exons2 = adjustForProteinLength(translationLength, exons);
+          dnaToProteinMapping = new Mapping(product, exons2,
                   new int[]
                   { 1, translationLength }, 3, 1);
           if (product != null)
@@ -666,7 +658,7 @@ public abstract class EmblXmlSource extends EbiFileRetrievedProxy
       return listToArray(ranges);
     } catch (ParseException e)
     {
-      Cache.log.warn(
+      Console.warn(
               String.format("Not parsing inexact CDS location %s in ENA %s",
                       location, accession));
       return new int[] {};
@@ -759,8 +751,7 @@ public abstract class EmblXmlSource extends EbiFileRetrievedProxy
 
   /**
    * Truncates (if necessary) the exon intervals to match 3 times the length of
-   * the protein; also accepts 3 bases longer (for stop codon not included in
-   * protein)
+   * the protein (including truncation for stop codon included in exon)
    * 
    * @param proteinLength
    * @param exon
@@ -777,11 +768,9 @@ public abstract class EmblXmlSource extends EbiFileRetrievedProxy
     int exonLength = MappingUtils.getLength(Arrays.asList(exon));
 
     /*
-     * if exon length matches protein, or is shorter, or longer by the 
-     * length of a stop codon (3 bases), then leave it unchanged
+     * if exon length matches protein, or is shorter, then leave it unchanged
      */
-    if (expectedCdsLength >= exonLength
-            || expectedCdsLength == exonLength - 3)
+    if (expectedCdsLength >= exonLength)
     {
       return exon;
     }
index 9340f65..e39f0ab 100644 (file)
@@ -22,7 +22,7 @@ package jalview.ws.dbsources;
 
 import java.util.Locale;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.io.DataSourceType;
@@ -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);
-    }
+    Console.debug("XFAM URL for retrieval is: " + xfamUrl);
 
     AlignmentI rcds = new FormatAdapter().readFile(xfamUrl,
             DataSourceType.URL, FileFormat.Stockholm);
index bee9fad..4a8f512 100644 (file)
@@ -20,6 +20,8 @@
  */
 package jalview.ws.jws1;
 
+import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.JvOptionPane;
 import jalview.util.MessageManager;
 
@@ -98,7 +100,7 @@ public class Discoverer implements Runnable
       // timeout
     } catch (Exception ex)
     {
-      jalview.bin.Cache.log.error(
+      Console.error(
               "Serious!  Service location failed\nfor URL :" + WsURL + "\n",
               ex);
 
@@ -126,7 +128,7 @@ public class Discoverer implements Runnable
   static private Vector<URL> getDiscoveryURLS()
   {
     Vector<URL> 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 +146,21 @@ public class Discoverer implements Runnable
           }
           else
           {
-            jalview.bin.Cache.log
-                    .info("Ignoring duplicate url in DISCOVERY_URLS list");
+            Console.info("Ignoring duplicate url in DISCOVERY_URLS list");
           }
         } catch (Exception ex)
         {
-          jalview.bin.Cache.log
-                  .warn("Problem whilst trying to make a URL from '"
+          Console.warn("Problem whilst trying to make a URL from '"
                           + ((url != null) ? url : "<null>") + "'");
-          jalview.bin.Cache.log.warn(
+          Console.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);
+          Console.debug("Exception was ", ex);
         }
       }
     } catch (Exception ex)
     {
-      jalview.bin.Cache.log.warn(
+      Console.warn(
               "Error parsing comma separated list of urls in DISCOVERY_URLS.",
               ex);
     }
@@ -176,11 +176,10 @@ public class Discoverer implements Runnable
    */
   static public void doDiscovery()
   {
-    jalview.bin.Cache.log
-            .debug("(Re)-Initialising the discovery URL list.");
+    Console.debug("(Re)-Initialising the discovery URL list.");
     try
     {
-      reallyDiscoverServices = jalview.bin.Cache
+      reallyDiscoverServices = Cache
               .getDefault("DISCOVERY_START", false);
       if (reallyDiscoverServices)
       {
@@ -188,7 +187,7 @@ public class Discoverer implements Runnable
       }
       else
       {
-        jalview.bin.Cache.log.debug("Setting default services");
+        Console.debug("Setting default services");
         services = new Hashtable<>();
         // Muscle, Clustal and JPred.
         ServiceHandle[] defServices = { new ServiceHandle("MsaWS",
@@ -239,7 +238,7 @@ public class Discoverer implements Runnable
     ServiceHandles shs = null;
     try
     {
-      jalview.bin.Cache.log.debug("Discovering services using " + location);
+      Console.debug("Discovering services using " + location);
       shs = locateWebService(location).getServices();
     } catch (org.apache.axis.AxisFault f)
     {
@@ -257,13 +256,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);
+        Console.warn("No Discovery service at " + location);
+        Console.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);
+      Console.warn("No Discovery service at " + location);
+      Console.debug("Discovery Service General Exception", e);
     }
     if ((shs != null) && shs.getServices().length > 0)
     {
@@ -293,7 +292,7 @@ public class Discoverer implements Runnable
     {
       if (!cat.contains(sh[i]))
       {
-        jalview.bin.Cache.log.debug("A " + sh[i].getAbstractName()
+        Console.debug("A " + sh[i].getAbstractName()
                 + " service called " + sh[i].getName() + " exists at "
                 + sh[i].getEndpointURL() + "\n");
         if (!sscat.containsKey(sh[i].getAbstractName()))
@@ -315,15 +314,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(
+                Console.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 "
+              Console.debug("Ignoring bad discovery service URL "
                               + sh[i].getEndpointURL(), e);
             }
           }
@@ -341,8 +339,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.");
+      Console.debug("No service endpoints to use for service discovery.");
       return;
     }
     while (s_url < ServiceURLList.size())
@@ -355,7 +352,7 @@ public class Discoverer implements Runnable
       }
       else
       {
-        jalview.bin.Cache.log.warn("No services at "
+        Console.warn("No services at "
                 + (ServiceURLList.get(s_url))
                 + " - check DISCOVERY_URLS property in .jalview_properties");
       }
index e9c2aea..cc73d24 100644 (file)
@@ -23,7 +23,7 @@ package jalview.ws.jws1;
 import java.util.Locale;
 
 import jalview.analysis.AlignSeq;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.SeqCigar;
 import jalview.datamodel.SequenceI;
@@ -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!");
+      Console.warn("Couldn't find a Jpred webservice to invoke!");
       return;
     }
     SeqCigar[] msf = null;
index 23d9eb0..a39945e 100644 (file)
@@ -22,7 +22,7 @@ package jalview.ws.jws1;
 
 import jalview.analysis.AlignSeq;
 import jalview.analysis.SeqsetUtils;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
@@ -119,17 +119,17 @@ class JPredThread extends JWS1Thread implements WSClientI
 
       JpredResult result = (JpredResult) this.result;
 
-      Cache.log.debug("Parsing output from JNet job.");
+      Console.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.");
+      Console.debug("Got prediction profile.");
 
       if ((this.msa != null) && (result.getAligfile() != null))
       {
-        Cache.log.debug("Getting associated alignment.");
+        Console.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() + "'");
+          Console.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);
+        Console.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);
+        Console.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(
+      Console.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);
+            Console.debug("Parsing output of job " + jn);
             jobres = j.getResultSet();
-            jalview.bin.Cache.log.debug("Finished parsing output.");
+            Console.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);
+            Console.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.");
+          Console.info("Append results onto existing alignment.");
         }
       }
     }
index 006f014..e027038 100644 (file)
@@ -21,7 +21,7 @@
 package jalview.ws.jws1;
 
 import jalview.analysis.AlignSeq;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentOrder;
@@ -410,7 +410,7 @@ class MsaWSThread extends JWS1Thread implements WSClientI
           {
             cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
                     + exc + "\n");
-            Cache.log.warn(
+            Console.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 (Console.isDebugEnabled())
       {
-        Cache.log.debug(
+        Console.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(
+      Console.error(
               "Unexpected exception when processing results for " + alTitle,
               ex);
       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
index 53338d3..0c67063 100644 (file)
@@ -20,6 +20,7 @@
  */
 package jalview.ws.jws1;
 
+import jalview.bin.Console;
 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(
+      Console.warn(
               "Database list request failed, so disabling SeqSearch Service client "
                       + sh.getName() + " at " + sh.getEndpointURL(),
               e);
index 761b758..0f28230 100644 (file)
@@ -22,7 +22,7 @@ package jalview.ws.jws1;
 
 import jalview.analysis.AlignSeq;
 import jalview.api.FeatureColourI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
@@ -425,7 +425,7 @@ class SeqSearchWSThread extends JWS1Thread implements WSClientI
           {
             cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
                     + exc + "\n");
-            Cache.log.warn(
+            Console.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 (Console.isDebugEnabled())
       {
-        Cache.log.debug(
+        Console.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(
+      Console.error(
               "Unexpected exception when processing results for " + alTitle,
               ex);
       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
index a1b8e7a..315e69f 100644 (file)
@@ -21,7 +21,7 @@
 package jalview.ws.jws2;
 
 import jalview.api.FeatureColourI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.GraphLine;
 import jalview.datamodel.SequenceFeature;
@@ -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 "
+          Console.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.");
index dd64e77..4ed92fb 100644 (file)
@@ -24,6 +24,7 @@ import jalview.analysis.AlignSeq;
 import jalview.analysis.SeqsetUtils;
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
+import jalview.bin.Console;
 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 "
+          Console.debug("Updating result annotation from Job "
                   + rslt + " at " + service.getUri());
           updateResultAnnotation(true);
           ap.adjustAnnotationHeight();
index d06c3f0..5831df8 100644 (file)
@@ -23,7 +23,7 @@
  */
 package jalview.ws.jws2;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.ws.jws2.jabaws2.Jws2Instance;
 import jalview.ws.jws2.jabaws2.Jws2InstanceFactory;
 
@@ -212,16 +212,16 @@ public class JabaWsServerQuery implements Runnable
       else
       {
         jws2Discoverer.addInvalidServiceUrl(jwsserver);
-        Cache.log.warn("Ignoring invalid Jws2 service url " + jwsserver);
+        Console.warn("Ignoring invalid Jws2 service url " + jwsserver);
       }
     } catch (Exception e)
     {
       e.printStackTrace();
-      Cache.log.warn("Exception when discovering Jws2 services.", e);
+      Console.warn("Exception when discovering Jws2 services.", e);
       jws2Discoverer.addInvalidServiceUrl(jwsserver);
     } catch (Error e)
     {
-      Cache.log.error("Exception when discovering Jws2 services.", e);
+      Console.error("Exception when discovering Jws2 services.", e);
       jws2Discoverer.addInvalidServiceUrl(jwsserver);
     }
     running = false;
index 71ba1b9..2f996bd 100644 (file)
@@ -32,7 +32,7 @@ import javax.swing.event.MenuListener;
 
 import compbio.metadata.Argument;
 import jalview.api.AlignCalcWorkerI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
 import jalview.gui.JvSwingUtils;
@@ -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
+        Console.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(
+        Console.warn(
                 "Ignoring invalid preferred service for AACon calculations (service type was "
                         + service.serviceType + ")");
         service = null;
index 516a719..d624c5c 100644 (file)
@@ -21,6 +21,7 @@
 package jalview.ws.jws2;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
 import jalview.gui.JvSwingUtils;
@@ -164,7 +165,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
       {
         try
         {
-          Cache.log.debug(
+          Console.debug(
                   "Waiting around for old discovery thread to finish.");
           // wait around until old discoverer dies
           Thread.sleep(100);
@@ -173,7 +174,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
         }
       }
       aborted = false;
-      Cache.log.debug("Old discovery thread has finished.");
+      Console.debug("Old discovery thread has finished.");
     }
     running = true;
 
@@ -258,7 +259,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
       }
       if (aborted)
       {
-        Cache.log.debug(
+        Console.debug(
                 "Aborting " + qrys.size() + " JABAWS discovery threads.");
         for (JabaWsServerQuery squery : qrys)
         {
@@ -711,23 +712,23 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
           }
           else
           {
-            Cache.log.warn("Ignoring duplicate url " + url + " in "
+            Console.warn("Ignoring duplicate url " + url + " in "
                     + JWS2HOSTURLS + " list");
           }
         } catch (MalformedURLException ex)
         {
-          Cache.log.warn("Problem whilst trying to make a URL from '"
+          Console.warn("Problem whilst trying to make a URL from '"
                   + ((url != null) ? url : "<null>") + "'");
-          Cache.log.warn(
+          Console.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);
+          Console.debug("Exception was ", ex);
         }
       }
     } catch (Exception ex)
     {
-      Cache.log.warn("Error parsing comma separated list of urls in "
+      Console.warn("Error parsing comma separated list of urls in "
               + JWS2HOSTURLS + " preference.", ex);
     }
     return urls;
index db6e03f..ee0fbc5 100644 (file)
@@ -21,7 +21,7 @@
 package jalview.ws.jws2;
 
 import jalview.analysis.AlignSeq;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentOrder;
@@ -574,7 +574,7 @@ class MsaWSThread extends AWS2Thread implements WSClientI
           {
             cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
                     + exc + "\n");
-            Cache.log.warn(
+            Console.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 (Console.isDebugEnabled())
       {
-        Cache.log.debug(
+        Console.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(
+              Console.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 (Console.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(
+            Console.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);
+            Console.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(
+      Console.error(
               "Unexpected exception when processing results for " + alTitle,
               ex);
       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
index 5bfe3b5..bd2f664 100644 (file)
@@ -20,7 +20,7 @@
  */
 package jalview.ws.rest;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.io.FileParse;
 import jalview.io.packed.DataProvider;
 import jalview.io.packed.DataProvider.JvDataType;
@@ -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);
+        Console.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());
+        Console.debug("Result Type: " + en.getContentType().toString());
       }
       else
       {
-        Cache.log.debug("No Result Type Specified.");
+        Console.debug("No Result Type Specified.");
       }
       if (enc == null || enc.length() < 1)
       {
-        Cache.log.debug("Assuming 'Default' Result Encoding.");
+        Console.debug("Assuming 'Default' Result Encoding.");
       }
       else
       {
-        Cache.log.debug("Result Encoded as : " + enc);
+        Console.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
+        Console.error("Can't handle encoding '" + enc
                 + "' for response from webservice.", e);
         en.consumeContent();
         error = true;
index a71b70d..fdab105 100644 (file)
@@ -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());
index 20b517b..f32535c 100644 (file)
@@ -22,7 +22,7 @@ package jalview.ws.rest;
 
 import java.util.Locale;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
@@ -268,7 +268,7 @@ public class RestJobThread extends AWSThread
                 + "</a><br>See Console output for details.";
         rj.setAllowedServerExceptions(0);// unrecoverable;
         rj.error = true;
-        Cache.log.fatal("Unexpected REST Job " + getStage(stg)
+        Console.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. <br>Problematic url was <a href=\""
                 + request.getURI() + "\">" + request.getURI()
                 + "</a><br>See Console output for details.";
-        Cache.log.warn("IO Exception for REST Job " + getStage(stg)
+        Console.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.");
+        Console.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)
+            Console.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)
+        Console.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
                   + "</a><br/>Filtered response content below:<br/>");
         } catch (IOException e)
         {
-          Cache.log.debug("IOException when consuming unhandled response",
+          Console.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);
+      Console.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!");
+    Console.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());
+          Console.debug("Parsing data for job " + rj.getJobId());
           rj.parseResultSet();
           if (rj.hasResults())
           {
             validres++;
           }
-          Cache.log.debug("Finished parsing data for job " + rj.getJobId());
+          Console.debug("Finished parsing data for job " + rj.getJobId());
 
         } catch (Error ex)
         {
-          Cache.log.warn(
+          Console.warn(
                   "Failed to finish parsing data for job " + rj.getJobId());
           ex.printStackTrace();
         } catch (Exception ex)
         {
-          Cache.log.warn(
+          Console.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(
+                Console.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(
+                      Console.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(
+                    Console.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(
+                Console.error(
                         "Tree recovery from restjob not yet implemented.");
               }
             }
index 2a27cce..5b80541 100644 (file)
@@ -21,7 +21,7 @@
 package jalview.ws.seqfetcher;
 
 import jalview.api.FeatureSettingsModelI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.SequenceI;
@@ -112,7 +112,7 @@ public class ASequenceFetcher
         return true;
       }
     }
-    Cache.log.warn("isFetchable doesn't know about '" + source + "'");
+    Console.warn("isFetchable doesn't know about '" + source + "'");
     return false;
   }
 
index 2ca112f..4bd38d2 100644 (file)
@@ -415,15 +415,19 @@ public class CrossRefTest
   @Test(groups = { "Functional_Failing" })
   public void testFindXrefSequences_withFetch()
   {
+    // JBPNote: this fails because pep1 and pep2 do not have DbRefEntrys with mappings
+    // Fix#1 would be to revise the test data so it fits with 2.11.2+ Jalview assumptions
+    // that ENA retrievals yield dbrefs with Mappings
+    
     SequenceI dna1 = new Sequence("AF039662", "GGGGCAGCACAAGAAC");
     dna1.addDBRef(new DBRefEntry("UNIPROT", "ENA:0", "Q9ZTS2"));
     dna1.addDBRef(new DBRefEntry("UNIPROT", "ENA:0", "P30419"));
     dna1.addDBRef(new DBRefEntry("UNIPROT", "ENA:0", "P00314"));
     final SequenceI pep1 = new Sequence("Q9ZTS2", "MYQLIRSSW");
-    pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2"));
+    pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "Q9ZTS2",null,true));
 
     final SequenceI pep2 = new Sequence("P00314", "MRKLLAASG");
-    pep2.addDBRef(new DBRefEntry("UNIPROT", "0", "P00314"));
+    pep2.addDBRef(new DBRefEntry("UNIPROT", "0", "P00314",null,true));
 
     /*
      * argument false suppresses adding DAS sources
index a539f78..4323699 100644 (file)
@@ -253,7 +253,7 @@ public class CommandLineOperations
     {
       System.out.println(ln);
       successfulCMDs.add(ln);
-      if (++count > 25)
+      if (++count > 50)
       {
         break;
       }
@@ -275,7 +275,7 @@ public class CommandLineOperations
 
   @Test(
     groups =
-    { "Functional", "testben" },
+    { "Functional" },
     dataProvider = "headlessModeOutputOperationsData")
   public void testHeadlessModeOutputOperations(String harg, String type,
           String fileName, boolean withAWT, int expectedMinFileSize,
index 71d13d0..470ec35 100644 (file)
@@ -162,7 +162,7 @@ public class HiDPISettingTest2
   @Test(groups = { "Functional" }, dataProvider = "hidpiScaleArguments")
   public void testHiDPISettings(int scale)
   {
-    if (Platform.isLinux())
+    if (!Platform.isLinux())
     {
       throw new SkipException(
               "Not linux platform, not testing actual scaling with "
index f8479a3..bd5e9ac 100644 (file)
@@ -48,8 +48,8 @@ public class SequenceFeatureTest
   @Test(groups = { "Functional" })
   public void testCopyConstructors()
   {
-    SequenceFeature sf1 = new SequenceFeature("type", "desc", 22, 33,
-            12.5f, "group");
+    SequenceFeature sf1 = new SequenceFeature("type", "desc", 22, 33, 12.5f,
+            "group");
     sf1.setValue("STRAND", "+");
     sf1.setValue("Note", "Testing");
     Integer count = Integer.valueOf(7);
@@ -83,8 +83,8 @@ public class SequenceFeatureTest
     /*
      * copy constructor modifying type/begin/end/group/score
      */
-    SequenceFeature sf4 = new SequenceFeature(sf1, "Disulfide bond", 12,
-            15, "group3", -9.1f);
+    SequenceFeature sf4 = new SequenceFeature(sf1, "Disulfide bond", 12, 15,
+            "group3", -9.1f);
     assertEquals("Disulfide bond", sf4.getType());
     assertTrue(sf4.isContactFeature());
     assertEquals("desc", sf4.getDescription());
@@ -104,8 +104,8 @@ public class SequenceFeatureTest
   @Test(groups = { "Functional" })
   public void testGetValue()
   {
-    SequenceFeature sf1 = new SequenceFeature("type", "desc", 22, 33,
-            12.5f, "group");
+    SequenceFeature sf1 = new SequenceFeature("type", "desc", 22, 33, 12.5f,
+            "group");
     sf1.setValue("STRAND", "+");
     assertEquals("+", sf1.getValue("STRAND"));
     assertNull(sf1.getValue("strand")); // case-sensitive
@@ -137,15 +137,15 @@ public class SequenceFeatureTest
   @Test(groups = { "Functional" })
   public void testEqualsAndHashCode()
   {
-    SequenceFeature sf1 = new SequenceFeature("type", "desc", 22, 33,
-            12.5f, "group");
+    SequenceFeature sf1 = new SequenceFeature("type", "desc", 22, 33, 12.5f,
+            "group");
     sf1.setValue("ID", "id");
     sf1.setValue("Name", "name");
     sf1.setValue("Parent", "parent");
     sf1.setStrand("+");
     sf1.setPhase("1");
-    SequenceFeature sf2 = new SequenceFeature("type", "desc", 22, 33,
-            12.5f, "group");
+    SequenceFeature sf2 = new SequenceFeature("type", "desc", 22, 33, 12.5f,
+            "group");
     sf2.setValue("ID", "id");
     sf2.setValue("Name", "name");
     sf2.setValue("Parent", "parent");
@@ -158,10 +158,10 @@ public class SequenceFeatureTest
     assertEquals(sf1.hashCode(), sf2.hashCode());
 
     // changing type breaks equals:
-    SequenceFeature sf3 = new SequenceFeature("type", "desc", 22, 33,
-            12.5f, "group");
-    SequenceFeature sf4 = new SequenceFeature("Type", "desc", 22, 33,
-            12.5f, "group");
+    SequenceFeature sf3 = new SequenceFeature("type", "desc", 22, 33, 12.5f,
+            "group");
+    SequenceFeature sf4 = new SequenceFeature("Type", "desc", 22, 33, 12.5f,
+            "group");
     assertFalse(sf3.equals(sf4));
 
     // changing description breaks equals:
@@ -195,7 +195,8 @@ public class SequenceFeatureTest
 
     // changing start position breaks equals:
     int restorei = sf2.getBegin();
-    sf2 = new SequenceFeature(sf2, 21, sf2.getEnd(), sf2.getFeatureGroup(), sf2.getScore());
+    sf2 = new SequenceFeature(sf2, 21, sf2.getEnd(), sf2.getFeatureGroup(),
+            sf2.getScore());
     assertFalse(sf1.equals(sf2));
     sf2 = new SequenceFeature(sf2, restorei, sf2.getEnd(),
             sf2.getFeatureGroup(), sf2.getScore());
@@ -210,9 +211,11 @@ public class SequenceFeatureTest
 
     // changing feature group breaks equals:
     restores = sf2.getFeatureGroup();
-    sf2 = new SequenceFeature(sf2, sf2.getBegin(), sf2.getEnd(), "Group", sf2.getScore());
+    sf2 = new SequenceFeature(sf2, sf2.getBegin(), sf2.getEnd(), "Group",
+            sf2.getScore());
     assertFalse(sf1.equals(sf2));
-    sf2 = new SequenceFeature(sf2, sf2.getBegin(), sf2.getEnd(), restores, sf2.getScore());
+    sf2 = new SequenceFeature(sf2, sf2.getBegin(), sf2.getEnd(), restores,
+            sf2.getScore());
 
     // changing ID breaks equals:
     restores = (String) sf2.getValue("ID");
@@ -285,7 +288,8 @@ public class SequenceFeatureTest
     String seqName = seq.getName();
 
     // single locus, no group, no score
-    SequenceFeature sf = new SequenceFeature("variant", "G,C", 22, 22, null);
+    SequenceFeature sf = new SequenceFeature("variant", "G,C", 22, 22,
+            null);
     String expected = "<br><table><tr><td>Location</td><td>TestSeq</td><td>22</td></tr>"
             + "<tr><td>Type</td><td>variant</td><td></td></tr>"
             + "<tr><td>Description</td><td>G,C</td><td></td></tr></table>";
@@ -299,8 +303,7 @@ public class SequenceFeatureTest
             + "<tr><td>Description</td><td>a description</td><td></td></tr></table>";
     assertEquals(expected, sf.getDetailsReport(seqName, null));
 
-    sf = new SequenceFeature("variant", "G,C", 22, 33,
-            12.5f, "group");
+    sf = new SequenceFeature("variant", "G,C", 22, 33, 12.5f, "group");
     sf.setValue("Parent", "ENSG001");
     sf.setValue("Child", "ENSP002");
     expected = "<br><table><tr><td>Location</td><td>TestSeq</td><td>22-33</td></tr>"
@@ -351,9 +354,23 @@ public class SequenceFeatureTest
             + "<tr><td>Type</td><td>variant</td><td></td></tr>"
             + "<tr><td>Description</td><td>G,C</td><td></td></tr>"
             + "<tr><td>Consequence</td><td><i>Translated by Jalview</i></td><td>p.Leu9Phe</td></tr>"
-            + "<tr><td>alleles</td><td></td><td>G,C</td></tr>"
+            + "<tr><td>alleles</td><td></td><td>G,C</td></tr>" 
             + "</table>";
 
     assertEquals(expected, sf.getDetailsReport(seq.getName(), mf));
+    
+
+    /*
+     * exon feature extending beyond mapped range; mapped location should be
+     * restricted to peptide mapped range limit i.e. 10-13
+     */
+    SequenceFeature sf2 = new SequenceFeature("exon", "exon 1", 109, 230, null);
+    features.add(sf2);
+    expected = "<br><table><tr><td>Location</td><td>Cds</td><td>109-230</td></tr>"
+            + "<tr><td>Peptide Location</td><td>TestSeq</td><td>10-13</td></tr>"
+            + "<tr><td>Type</td><td>exon</td><td></td></tr>"
+            + "<tr><td>Description</td><td>exon 1</td><td></td></tr>"
+            + "</table>";
+    assertEquals(expected, sf2.getDetailsReport(seq.getName(), mf));
   }
 }
index bcd5784..25dcac1 100644 (file)
@@ -20,8 +20,6 @@
  */
 package jalview.gui;
 
-import jalview.bin.Cache;
-
 import java.awt.Dimension;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
@@ -35,6 +33,8 @@ import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
+import jalview.bin.Console;
+
 public class JAL1353bugdemo
 {
 
@@ -60,7 +60,7 @@ public class JAL1353bugdemo
   @Test(groups = { "Functional" }, enabled = false)
   public void test()
   {
-    Cache.initLogger();
+    Console.initLogger();
     // final Desktop foo = new Desktop();
     final JFrame cfoo = new JFrame("Crash Java");
     final JDesktopPane foo = new JDesktopPane();
index cc13fb9..b2d5b0a 100644 (file)
@@ -46,6 +46,7 @@ import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.Annotation;
@@ -94,7 +95,7 @@ public class PopupMenuTest
   public void setUp() throws IOException
   {
     Cache.loadProperties("test/jalview/io/testProps.jvprops");
-    Cache.initLogger();
+    Console.initLogger();
 
     String inMenuString = ("EMBL-EBI Search | http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$"
             + SEQUENCE_ID
index 7775c8f..f36e935 100644 (file)
@@ -17,7 +17,7 @@ import java.util.Set;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.Mapping;
 import jalview.datamodel.Sequence.DBModList;
@@ -31,7 +31,7 @@ public class EmblFlatFileTest
   @BeforeClass(alwaysRun = true)
   public void setUp()
   {
-    Cache.initLogger();
+    Console.initLogger();
   }
 
   /**
@@ -172,7 +172,7 @@ public class EmblFlatFileTest
         {
           assertEquals((ranges = map.getFromRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 1579);
-          assertEquals(ranges.get(0)[1], 2934);
+          assertEquals(ranges.get(0)[1], 2931);  // excludes stop 2934 
           assertEquals((ranges = map.getToRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 1);
           assertEquals(ranges.get(0)[1], 451);
@@ -184,7 +184,7 @@ public class EmblFlatFileTest
         {
           assertEquals((ranges = map.getFromRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 2928);
-          assertEquals(ranges.get(0)[1], 3992);
+          assertEquals(ranges.get(0)[1], 3989);  // excludes stop 3992
           assertEquals((ranges = map.getToRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 1);
           assertEquals(ranges.get(0)[1], 354);
@@ -193,7 +193,7 @@ public class EmblFlatFileTest
         {
           assertEquals((ranges = map.getFromRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 4054);
-          assertEquals(ranges.get(0)[1], 4848);
+          assertEquals(ranges.get(0)[1], 4845); // excludes stop 4848
           assertEquals((ranges = map.getToRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 1);
           assertEquals(ranges.get(0)[1], 264);
@@ -205,7 +205,7 @@ public class EmblFlatFileTest
           assertEquals(ranges.get(0)[0], 7022);
           assertEquals(ranges.get(0)[1], 7502);
           assertEquals(ranges.get(1)[0], 1);
-          assertEquals(ranges.get(1)[1], 437);
+          assertEquals(ranges.get(1)[1], 434); // excludes stop at 437
           assertEquals((ranges = map.getToRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 1);
           assertEquals(ranges.get(0)[1], 305);
@@ -215,7 +215,7 @@ public class EmblFlatFileTest
           // complement(488..1480)
           assertEquals((ranges = map.getFromRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 1480);
-          assertEquals(ranges.get(0)[1], 488);
+          assertEquals(ranges.get(0)[1], 491); // // excludes stop at 488
           assertEquals((ranges = map.getToRanges()).size(), 1);
           assertEquals(ranges.get(0)[0], 1);
           assertEquals(ranges.get(0)[1], 330);
@@ -329,21 +329,23 @@ public class EmblFlatFileTest
     // exact length match:
     assertSame(exons, EmblFlatFile.adjustForProteinLength(6, exons));
 
-    // match if we assume exons include stop codon not in protein:
-    assertSame(exons, EmblFlatFile.adjustForProteinLength(5, exons));
-
+    // patch from JAL-3725 in EmblXmlSource propagated to Flatfile
+    // match if we assume exons include stop codon not in protein: 
+    int[] truncated = EmblFlatFile.adjustForProteinLength(5, exons);
+    assertEquals(Arrays.toString(truncated), "[11, 15, 21, 25, 31, 35]");
+    
     // truncate last exon by 6bp
-    int[] truncated = EmblFlatFile.adjustForProteinLength(4, exons);
-    assertEquals("[11, 15, 21, 25, 31, 32]", Arrays.toString(truncated));
+    truncated = EmblFlatFile.adjustForProteinLength(4, exons);
+    assertEquals(Arrays.toString(truncated),"[11, 15, 21, 25, 31, 32]");
 
     // remove last exon and truncate preceding by 1bp (so 3bp in total)
     truncated = EmblFlatFile.adjustForProteinLength(3, exons);
-    assertEquals("[11, 15, 21, 24]", Arrays.toString(truncated));
+    assertEquals(Arrays.toString(truncated),"[11, 15, 21, 24]");
 
     // exact removal of exon case:
     exons = new int[] { 11, 15, 21, 27, 33, 38 }; // 18 bp
     truncated = EmblFlatFile.adjustForProteinLength(4, exons);
-    assertEquals("[11, 15, 21, 27]", Arrays.toString(truncated));
+    assertEquals(Arrays.toString(truncated), "[11, 15, 21, 27]");
 
     // what if exons are too short for protein?
     truncated = EmblFlatFile.adjustForProteinLength(7, exons);
index e37ae3f..b693d51 100644 (file)
@@ -36,7 +36,7 @@ import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.JvOptionPane;
 
 /**
@@ -59,7 +59,7 @@ public class FileIOTester
   @BeforeClass(alwaysRun = true)
   public static void setUpBeforeClass() throws Exception
   {
-    Cache.initLogger();
+    Console.initLogger();
   }
 
   /**
index 97e4754..83d630f 100644 (file)
@@ -13,7 +13,7 @@ import java.util.Set;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.Mapping;
 import jalview.datamodel.SequenceFeature;
@@ -26,7 +26,7 @@ public class GenBankFileTest
   @BeforeClass(alwaysRun = true)
   public void setUp()
   {
-    Cache.initLogger();
+    Console.initLogger();
   }
 
   /**
@@ -193,7 +193,7 @@ public class GenBankFileTest
     assertTrue(seqString.endsWith("FKQKS"));
     map = mapping.getMap();
     assertEquals(map.getFromLowest(), 6045);
-    assertEquals(map.getFromHighest(), 6788);
+    assertEquals(map.getFromHighest(), 6785); // excludes stop at 6788
     assertEquals(map.getToLowest(), 1);
     assertEquals(map.getToHighest(), 247);
     assertEquals(map.getFromRatio(), 3);
index a719cc4..a2bb08e 100644 (file)
@@ -6,6 +6,7 @@ import static org.testng.Assert.assertNull;
 import static org.testng.Assert.assertTrue;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.Mapping;
@@ -86,7 +87,7 @@ public class VCFLoaderTest
     Cache.setProperty("VCF_FIELDS", ".*");
     Cache.setProperty("VEP_FIELDS", ".*");
     Cache.setProperty("VCF_ASSEMBLY", "GRCh38=GRCh38");
-    Cache.initLogger();
+    Console.initLogger();
   }
 
   @BeforeTest(alwaysRun = true)
diff --git a/test/jalview/util/Log4jTest.java b/test/jalview/util/Log4jTest.java
new file mode 100644 (file)
index 0000000..73bf207
--- /dev/null
@@ -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 <http://www.gnu.org/licenses/>.
+ * 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.Console;
+
+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(Console.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 '"
+              + Console.LOGGING_TEST_MESSAGE + "'");
+    }
+  }
+
+}
index 3f1f7f3..9e494e1 100644 (file)
@@ -36,7 +36,7 @@ import java.util.List;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.JvOptionPane;
 
 public class MapListTest
@@ -44,7 +44,7 @@ public class MapListTest
   @BeforeClass(alwaysRun = true)
   public void setUp()
   {
-    Cache.initLogger();
+    Console.initLogger();
   }
   
   @BeforeClass(alwaysRun = true)
@@ -290,7 +290,7 @@ public class MapListTest
      * no overlap
      */
     assertNull(ml.locateInFrom(0, 0));
-    
+
   }
 
   /**
@@ -312,7 +312,7 @@ public class MapListTest
     assertEquals("[10, 10, 12, 12, 14, 14]",
             Arrays.toString(ml.locateInFrom(3, 3)));
     assertEquals("[16, 18]", Arrays.toString(ml.locateInFrom(4, 4)));
-    
+
     /*
      * codons at 11-16, 21-26, 31-36 mapped to peptide positions 1, 3-4, 6-8
      */
@@ -337,6 +337,86 @@ public class MapListTest
   }
 
   /**
+   * Tests for method that locates the overlap of the ranges in the 'from' map
+   * for given range in the 'to' map
+   */
+  @Test(groups = { "Functional" })
+  public void testGetOverlapsInFrom_withIntrons()
+  {
+    /*
+     * Exons at positions [2, 3, 5] [6, 7, 9] [10, 12, 14] [16, 17, 18] i.e.
+     * 2-3, 5-7, 9-10, 12-12, 14-14, 16-18
+     */
+    int[] codons = { 2, 3, 5, 7, 9, 10, 12, 12, 14, 14, 16, 18 };
+    int[] protein = { 11, 14 };
+    MapList ml = new MapList(codons, protein, 3, 1);
+
+    assertEquals("[2, 3, 5, 5]",
+            Arrays.toString(ml.getOverlapsInFrom(11, 11)));
+    assertEquals("[2, 3, 5, 7, 9, 9]",
+            Arrays.toString(ml.getOverlapsInFrom(11, 12)));
+    // out of range 5' :
+    assertEquals("[2, 3, 5, 7, 9, 9]",
+            Arrays.toString(ml.getOverlapsInFrom(8, 12)));
+    // out of range 3' :
+    assertEquals("[10, 10, 12, 12, 14, 14, 16, 18]",
+            Arrays.toString(ml.getOverlapsInFrom(13, 16)));
+    // out of range both :
+    assertEquals("[2, 3, 5, 7, 9, 10, 12, 12, 14, 14, 16, 18]",
+            Arrays.toString(ml.getOverlapsInFrom(1, 16)));
+    // no overlap:
+    assertNull(ml.getOverlapsInFrom(20, 25));
+  }
+
+  /**
+   * Tests for method that locates the overlap of the ranges in the 'to' map for
+   * given range in the 'from' map
+   */
+  @Test(groups = { "Functional" })
+  public void testGetOverlapsInTo_withIntrons()
+  {
+    /*
+     * Exons at positions [2, 3, 5] [6, 7, 9] [10, 12, 14] [17, 18, 19] i.e.
+     * 2-3, 5-7, 9-10, 12-12, 14-14, 17-19
+     */
+    int[] codons = { 2, 3, 5, 7, 9, 10, 12, 12, 14, 14, 17, 19 };
+    /*
+     * Mapped proteins at positions 1, 3, 4, 6 in the sequence
+     */
+    int[] protein = { 1, 1, 3, 4, 6, 6 };
+    MapList ml = new MapList(codons, protein, 3, 1);
+
+    /*
+     * Can't map from an unmapped position
+     */
+    assertNull(ml.getOverlapsInTo(1, 1));
+    assertNull(ml.getOverlapsInTo(4, 4));
+    assertNull(ml.getOverlapsInTo(15, 16));
+
+    /*
+     * nor from a range that includes no mapped position (exon)
+     */
+    assertNull(ml.getOverlapsInTo(15, 16));
+
+    // end of codon 1 maps to first peptide
+    assertEquals("[1, 1]", Arrays.toString(ml.getOverlapsInTo(2, 2)));
+    // end of codon 1 and start of codon 2 maps to first 2 peptides
+    assertEquals("[1, 1, 3, 3]", Arrays.toString(ml.getOverlapsInTo(3, 7)));
+
+    // range overlaps 5' end of dna:
+    assertEquals("[1, 1, 3, 3]", Arrays.toString(ml.getOverlapsInTo(1, 6)));
+    assertEquals("[1, 1, 3, 3]", Arrays.toString(ml.getOverlapsInTo(1, 8)));
+
+    // range overlaps 3' end of dna:
+    assertEquals("[6, 6]", Arrays.toString(ml.getOverlapsInTo(17, 24)));
+    assertEquals("[6, 6]", Arrays.toString(ml.getOverlapsInTo(16, 24)));
+
+    // dna positions 8, 11 are intron but include end of exon 2 and start of
+    // exon 3
+    assertEquals("[3, 4]", Arrays.toString(ml.getOverlapsInTo(8, 11)));
+  }
+
+  /**
    * Tests for method that locates ranges in the 'to' map for given range in the
    * 'from' map.
    */
@@ -376,7 +456,7 @@ public class MapListTest
      */
     assertEquals("[1, 4]", Arrays.toString(ml.locateInTo(1, 13)));
     assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(-1, 2)));
-    
+
     /*
      * no overlap
      */
@@ -422,7 +502,7 @@ public class MapListTest
     assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(1, 2)));
     assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(1, 4)));
     assertEquals("[1, 1]", Arrays.toString(ml.locateInTo(2, 4)));
-    
+
     /*
      * no overlap
      */
@@ -895,7 +975,7 @@ public class MapListTest
     toRanges = compound.getToRanges();
     assertEquals(2, toRanges.size());
     assertArrayEquals(new int[] { 931, 901 }, toRanges.get(0));
-    assertArrayEquals(new int[] { 600, 582}, toRanges.get(1));
+    assertArrayEquals(new int[] { 600, 582 }, toRanges.get(1));
 
     /*
      * 1:1 plus 1:3 should result in 1:3
@@ -1085,7 +1165,7 @@ public class MapListTest
      * no overlap
      */
     assertNull(ml.locateInTo(0, 0));
-    
+
     /*
      * partial overlap
      */
@@ -1101,7 +1181,7 @@ public class MapListTest
     ml = new MapList(gene, cds, 1, 1);
     assertEquals("[13203, 13204]",
             Arrays.toString(ml.locateInTo(13468, 13468)));
-    
+
     /*
      * gene to protein
      * the base at 13468 is in the codon for 4401N and also 4402R
@@ -1220,7 +1300,7 @@ public class MapListTest
   public void testAddOffsetPositions()
   {
     List<int[]> mapped = new ArrayList<>();
-    int[] range = new int[] {10, 20};
+    int[] range = new int[] { 10, 20 };
     BitSet offsets = new BitSet();
 
     MapList.addOffsetPositions(mapped, 0, range, offsets);
@@ -1262,7 +1342,7 @@ public class MapListTest
     assertArrayEquals(new int[] { 14, 13 }, mapped.get(1));
     assertArrayEquals(new int[] { 10, 10 }, mapped.get(2));
   }
-  
+
   @Test(groups = { "Functional" })
   public void testGetPositionsForOffsets()
   {
@@ -1270,28 +1350,28 @@ public class MapListTest
     BitSet offsets = new BitSet();
     List<int[]> mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertTrue(mapped.isEmpty()); // no ranges and no offsets!
-    
+
     offsets.set(5, 1000);
     mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertTrue(mapped.isEmpty()); // no ranges
-    
+
     /*
      * one range with overlap of offsets
      */
-    ranges.add(new int[] {15, 25});
+    ranges.add(new int[] { 15, 25 });
     mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertEquals(1, mapped.size());
-    assertArrayEquals(new int[] {20,  25}, mapped.get(0));
-    
+    assertArrayEquals(new int[] { 20, 25 }, mapped.get(0));
+
     /*
      * two ranges
      */
-    ranges.add(new int[] {300, 320});
+    ranges.add(new int[] { 300, 320 });
     mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertEquals(2, mapped.size());
-    assertArrayEquals(new int[] {20,  25}, mapped.get(0));
-    assertArrayEquals(new int[] {300, 320}, mapped.get(1));
-    
+    assertArrayEquals(new int[] { 20, 25 }, mapped.get(0));
+    assertArrayEquals(new int[] { 300, 320 }, mapped.get(1));
+
     /*
      * boundary case - right end of first range overlaps
      */
@@ -1299,45 +1379,45 @@ public class MapListTest
     offsets.set(10);
     mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertEquals(1, mapped.size());
-    assertArrayEquals(new int[] {25,  25}, mapped.get(0));
-    
+    assertArrayEquals(new int[] { 25, 25 }, mapped.get(0));
+
     /*
      * boundary case - left end of second range overlaps
      */
     offsets.set(11);
     mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertEquals(2, mapped.size());
-    assertArrayEquals(new int[] {25,  25}, mapped.get(0));
-    assertArrayEquals(new int[] {300, 300}, mapped.get(1));
-    
+    assertArrayEquals(new int[] { 25, 25 }, mapped.get(0));
+    assertArrayEquals(new int[] { 300, 300 }, mapped.get(1));
+
     /*
      * offsets into a circular range are reported in
      * the order in which they are traversed
      */
     ranges.clear();
-    ranges.add(new int[] {100, 150});
-    ranges.add(new int[] {60, 80});
+    ranges.add(new int[] { 100, 150 });
+    ranges.add(new int[] { 60, 80 });
     offsets.clear();
     offsets.set(45, 55); // sets bits 45 to 54
     mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertEquals(2, mapped.size());
-    assertArrayEquals(new int[] {145, 150}, mapped.get(0)); // offsets 45-50
-    assertArrayEquals(new int[] {60, 63}, mapped.get(1)); // offsets 51-54
+    assertArrayEquals(new int[] { 145, 150 }, mapped.get(0)); // offsets 45-50
+    assertArrayEquals(new int[] { 60, 63 }, mapped.get(1)); // offsets 51-54
 
     /*
      * reverse range overlap is reported with start < end
      */
     ranges.clear();
-    ranges.add(new int[] {4321, 4000});
+    ranges.add(new int[] { 4321, 4000 });
     offsets.clear();
     offsets.set(20, 22); // sets bits 20 and 21
     offsets.set(30);
     mapped = MapList.getPositionsForOffsets(ranges, offsets);
     assertEquals(2, mapped.size());
-    assertArrayEquals(new int[] {4301, 4300}, mapped.get(0));
-    assertArrayEquals(new int[] {4291, 4291}, mapped.get(1));
+    assertArrayEquals(new int[] { 4301, 4300 }, mapped.get(0));
+    assertArrayEquals(new int[] { 4291, 4291 }, mapped.get(1));
   }
-  
+
   @Test(groups = { "Functional" })
   public void testGetMappedOffsetsForPositions()
   {
@@ -1345,9 +1425,10 @@ public class MapListTest
      * start by verifying the examples in the method's Javadoc!
      */
     List<int[]> ranges = new ArrayList<>();
-    ranges.add(new int[] {10, 20});
-    ranges.add(new int[] {31, 40});
-    BitSet overlaps = MapList.getMappedOffsetsForPositions(1, 9, ranges, 1, 1);
+    ranges.add(new int[] { 10, 20 });
+    ranges.add(new int[] { 31, 40 });
+    BitSet overlaps = MapList.getMappedOffsetsForPositions(1, 9, ranges, 1,
+            1);
     assertTrue(overlaps.isEmpty());
     overlaps = MapList.getMappedOffsetsForPositions(1, 11, ranges, 1, 1);
     assertEquals(2, overlaps.cardinality());
@@ -1355,75 +1436,80 @@ public class MapListTest
     assertTrue(overlaps.get(1));
     overlaps = MapList.getMappedOffsetsForPositions(15, 35, ranges, 1, 1);
     assertEquals(11, overlaps.cardinality());
-    for (int i = 5 ; i <= 11 ; i++)
+    for (int i = 5; i <= 11; i++)
     {
       assertTrue(overlaps.get(i));
     }
-    
+
     ranges.clear();
-    ranges.add(new int[] {1, 200});
+    ranges.add(new int[] { 1, 200 });
     overlaps = MapList.getMappedOffsetsForPositions(9, 9, ranges, 1, 3);
     assertEquals(3, overlaps.cardinality());
     assertTrue(overlaps.get(24));
     assertTrue(overlaps.get(25));
     assertTrue(overlaps.get(26));
-    
+
     ranges.clear();
-    ranges.add(new int[] {101, 150});
-    ranges.add(new int[] {171, 180});
+    ranges.add(new int[] { 101, 150 });
+    ranges.add(new int[] { 171, 180 });
     overlaps = MapList.getMappedOffsetsForPositions(101, 102, ranges, 3, 1);
     assertEquals(1, overlaps.cardinality());
     assertTrue(overlaps.get(0));
     overlaps = MapList.getMappedOffsetsForPositions(150, 171, ranges, 3, 1);
     assertEquals(1, overlaps.cardinality());
     assertTrue(overlaps.get(16));
-    
+
     ranges.clear();
-    ranges.add(new int[] {101, 150});
-    ranges.add(new int[] {21, 30});
+    ranges.add(new int[] { 101, 150 });
+    ranges.add(new int[] { 21, 30 });
     overlaps = MapList.getMappedOffsetsForPositions(24, 40, ranges, 3, 1);
     assertEquals(3, overlaps.cardinality());
     assertTrue(overlaps.get(17));
     assertTrue(overlaps.get(18));
     assertTrue(overlaps.get(19));
-    
+
     /*
      * reverse range 1:1 (e.g. reverse strand gene to transcript)
      */
     ranges.clear();
-    ranges.add(new int[] {20, 10});
+    ranges.add(new int[] { 20, 10 });
     overlaps = MapList.getMappedOffsetsForPositions(12, 13, ranges, 1, 1);
     assertEquals(2, overlaps.cardinality());
     assertTrue(overlaps.get(7));
     assertTrue(overlaps.get(8));
-    
+
     /*
      * reverse range 3:1 (e.g. reverse strand gene to peptide)
      * from EMBL:J03321 to P0CE20
      */
     ranges.clear();
-    ranges.add(new int[] {1480, 488});
-    overlaps = MapList.getMappedOffsetsForPositions(1460, 1460, ranges, 3, 1);
+    ranges.add(new int[] { 1480, 488 });
+    overlaps = MapList.getMappedOffsetsForPositions(1460, 1460, ranges, 3,
+            1);
     // 1460 is the end of the 7th codon
     assertEquals(1, overlaps.cardinality());
     assertTrue(overlaps.get(6));
     // add one base (part codon)
-    overlaps = MapList.getMappedOffsetsForPositions(1459, 1460, ranges, 3, 1);
+    overlaps = MapList.getMappedOffsetsForPositions(1459, 1460, ranges, 3,
+            1);
     assertEquals(2, overlaps.cardinality());
     assertTrue(overlaps.get(6));
     assertTrue(overlaps.get(7));
     // add second base (part codon)
-    overlaps = MapList.getMappedOffsetsForPositions(1458, 1460, ranges, 3, 1);
+    overlaps = MapList.getMappedOffsetsForPositions(1458, 1460, ranges, 3,
+            1);
     assertEquals(2, overlaps.cardinality());
     assertTrue(overlaps.get(6));
     assertTrue(overlaps.get(7));
     // add third base (whole codon)
-    overlaps = MapList.getMappedOffsetsForPositions(1457, 1460, ranges, 3, 1);
+    overlaps = MapList.getMappedOffsetsForPositions(1457, 1460, ranges, 3,
+            1);
     assertEquals(2, overlaps.cardinality());
     assertTrue(overlaps.get(6));
     assertTrue(overlaps.get(7));
     // add one more base (part codon)
-    overlaps = MapList.getMappedOffsetsForPositions(1456, 1460, ranges, 3, 1);
+    overlaps = MapList.getMappedOffsetsForPositions(1456, 1460, ranges, 3,
+            1);
     assertEquals(3, overlaps.cardinality());
     assertTrue(overlaps.get(6));
     assertTrue(overlaps.get(7));
index bd81d30..1420cee 100644 (file)
@@ -22,19 +22,10 @@ package jalview.util;
 
 import static org.testng.AssertJUnit.assertEquals;
 import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNull;
 import static org.testng.AssertJUnit.assertSame;
 import static org.testng.AssertJUnit.assertTrue;
-import static org.testng.AssertJUnit.fail;
-
-import java.awt.Color;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
+import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
 
 import java.awt.Color;
 import java.io.IOException;
@@ -47,7 +38,7 @@ import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 import jalview.api.AlignViewportI;
-import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.commands.EditCommand;
 import jalview.commands.EditCommand.Action;
 import jalview.commands.EditCommand.Edit;
@@ -73,7 +64,7 @@ public class MappingUtilsTest
   @BeforeClass(alwaysRun = true)
   public void setUp()
   {
-    Cache.initLogger();
+    Console.initLogger();
   }
 
   @BeforeClass(alwaysRun = true)
@@ -1340,32 +1331,21 @@ public class MappingUtilsTest
   }
 
   @Test(groups = "Functional")
-  public void testListToArray()
+  public void testFindOverlap()
   {
     List<int[]> ranges = new ArrayList<>();
-
-    int[] result = MappingUtils.rangeListToArray(ranges);
-    assertEquals(result.length, 0);
-    ranges.add(new int[] { 24, 12 });
-    result = MappingUtils.rangeListToArray(ranges);
-    assertEquals(result.length, 2);
-    assertEquals(result[0], 24);
-    assertEquals(result[1], 12);
-    ranges.add(new int[] { -7, 30 });
-    result = MappingUtils.rangeListToArray(ranges);
-    assertEquals(result.length, 4);
-    assertEquals(result[0], 24);
-    assertEquals(result[1], 12);
-    assertEquals(result[2], -7);
-    assertEquals(result[3], 30);
-    try
-    {
-      MappingUtils.rangeListToArray(null);
-      fail("Expected exception");
-    } catch (NullPointerException e)
-    {
-      // expected
-    }
+    ranges.add(new int[] { 4, 8 });
+    ranges.add(new int[] { 10, 12 });
+    ranges.add(new int[] { 16, 19 });
+
+    int[] overlap = MappingUtils.findOverlap(ranges, 5, 13);
+    assertArrayEquals(overlap, new int[] { 5, 12 });
+    overlap = MappingUtils.findOverlap(ranges, -100, 100);
+    assertArrayEquals(overlap, new int[] { 4, 19 });
+    overlap = MappingUtils.findOverlap(ranges, 7, 17);
+    assertArrayEquals(overlap, new int[] { 7, 17 });
+    overlap = MappingUtils.findOverlap(ranges, 13, 15);
+    assertNull(overlap);
   }
   
   /**
diff --git a/test/jalview/util/log4jTestProps.jvprops b/test/jalview/util/log4jTestProps.jvprops
new file mode 100644 (file)
index 0000000..c640dd1
--- /dev/null
@@ -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
index a0991e5..236e0a5 100644 (file)
@@ -26,6 +26,14 @@ import static org.testng.AssertJUnit.assertNull;
 import static org.testng.AssertJUnit.assertSame;
 import static org.testng.AssertJUnit.assertTrue;
 
+import java.io.ByteArrayInputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.DBRefEntry;
 import jalview.datamodel.DBRefSource;
@@ -36,14 +44,6 @@ import jalview.xml.binding.embl.EntryType.Feature;
 import jalview.xml.binding.embl.EntryType.Feature.Qualifier;
 import jalview.xml.binding.embl.XrefType;
 
-import java.io.ByteArrayInputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
 public class EmblXmlSourceTest
 {
 
@@ -352,11 +352,12 @@ public class EmblXmlSourceTest
     // exact length match:
     assertSame(exons, EmblXmlSource.adjustForProteinLength(6, exons));
 
-    // match if we assume exons include stop codon not in protein:
-    assertSame(exons, EmblXmlSource.adjustForProteinLength(5, exons));
+    // truncate last exon by 3bp (e.g. stop codon)
+    int[] truncated = EmblXmlSource.adjustForProteinLength(5, exons);
+    assertEquals("[11, 15, 21, 25, 31, 35]", Arrays.toString(truncated));
 
     // truncate last exon by 6bp
-    int[] truncated = EmblXmlSource.adjustForProteinLength(4, exons);
+    truncated = EmblXmlSource.adjustForProteinLength(4, exons);
     assertEquals("[11, 15, 21, 25, 31, 32]", Arrays.toString(truncated));
 
     // remove last exon and truncate preceding by 1bp
index 2318971..f04326b 100644 (file)
@@ -23,6 +23,7 @@ package jalview.ws.gui;
 import java.util.Locale;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.JvOptionPane;
 import jalview.gui.WsJobParameters;
 import jalview.util.MessageManager;
@@ -77,7 +78,7 @@ public class Jws2ParamView
   public static void setUpBeforeClass() throws Exception
   {
     Cache.loadProperties("test/jalview/io/testProps.jvprops");
-    Cache.initLogger();
+    Console.initLogger();
     disc = JalviewJabawsTestUtils.getJabawsDiscoverer();
   }
 
index d13dc0f..5656a6d 100644 (file)
@@ -26,6 +26,7 @@ import static org.testng.AssertJUnit.assertNotNull;
 import static org.testng.AssertJUnit.assertTrue;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.gui.JvOptionPane;
@@ -75,7 +76,7 @@ public class DisorderAnnotExportImport
   public static void setUpBeforeClass() throws Exception
   {
     Cache.loadProperties("test/jalview/io/testProps.jvprops");
-    Cache.initLogger();
+    Console.initLogger();
     disc = JalviewJabawsTestUtils.getJabawsDiscoverer();
 
     while (disc.isRunning())
index cc9aba0..e66f016 100644 (file)
@@ -26,6 +26,7 @@ import static org.testng.AssertJUnit.assertNotNull;
 import static org.testng.AssertJUnit.assertTrue;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
 import jalview.gui.JvOptionPane;
@@ -88,7 +89,7 @@ public class RNAStructExportImport
   public static void setUpBeforeClass() throws Exception
   {
     Cache.loadProperties("test/jalview/io/testProps.jvprops");
-    Cache.initLogger();
+    Console.initLogger();
     disc = JalviewJabawsTestUtils.getJabawsDiscoverer(false);
 
     while (disc.isRunning())
index 51ff19c..052d62f 100644 (file)
@@ -27,6 +27,7 @@ import static org.testng.AssertJUnit.assertFalse;
 import static org.testng.AssertJUnit.assertTrue;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
 import jalview.gui.JvOptionPane;
 import jalview.ws.jabaws.JalviewJabawsTestUtils;
 import jalview.ws.jws2.jabaws2.Jws2Instance;
@@ -72,7 +73,7 @@ public class ParameterUtilsTest
   {
     serviceTests.add("AAConWS".toLowerCase(Locale.ROOT));
     Cache.loadProperties("test/jalview/io/testProps.jvprops");
-    Cache.initLogger();
+    Console.initLogger();
     disc = JalviewJabawsTestUtils.getJabawsDiscoverer();
   }
 
index 709f2c5..a9668a9 100644 (file)
@@ -75,7 +75,7 @@ public class ShmmrRSBSService
     RestClient rc = new RestClient(_rc.service, alf, true);
 
     assertNotNull("Couldn't creat RestClient job.", rc);
-    jalview.bin.Cache.initLogger();
+    jalview.bin.Console.initLogger();
     RestJob rjb = new RestJob(0, new RestJobThread(rc),
             rc.av.getAlignment(), null);
     rjb.setAlignmentForInputs(rc.service.getInputParams().values(),
index 914520f..b987e02 100644 (file)
@@ -68,7 +68,7 @@ public class DbRefFetcherTest
   @BeforeClass(alwaysRun = true)
   public static void setUpBeforeClass() throws Exception
   {
-    jalview.bin.Cache.initLogger();
+    jalview.bin.Console.initLogger();
   }
 
   /**
index 3e7e153..15b162f 100644 (file)
@@ -16,4 +16,4 @@ uod_banner.28=/images/UoD_banner-28.png
 uod_banner.30=/images/UoD_banner-30.png
 uod_banner.32=/images/UoD_banner-32.png
 default_appbase=https://www.jalview.org/getdown/release/1.8
-preferences.filename=.jalview_properties
+preferences.filename=.jalview_nonrelease_properties
index f281469..31a4afa 100755 (executable)
@@ -39,7 +39,7 @@ my $add_associations = {
   annotations => {shortname=>"annotations",name=>"Jalview Annotations",extensions=>["annotations","jvannotations"]},
   mmcif => {shortname=>"mmcif",name=>"CIF",extensions=>["cif"]},
   mmcif2 => {shortname=>"mmcif2",name=>"mmCIF",extensions=>["mcif","mmcif"]},
-  jvl => {shortname=>"jvl",name=>"Jalview Launch",extensions=>["jvl"],iconfile=>"Jalview-Launch"},
+  jvl => {shortname=>"jvl",name=>"Jalview Launch",extensions=>["jvl"],iconfile=>"jvl_file"},
   jnet => {shortname=>"jnet",name=>"JnetFile",extensions=>["concise","jnet"]},
   scorematrix => {shortname=>"scorematrix",name=>"Substitution Matrix",extensions=>["mat"]},
 };
index 2196a6a..0b927a8 100644 (file)
@@ -28,7 +28,7 @@
 <key>CFBundleTypeName</key>
 <string>Jalview Launch File</string>
 <key>CFBundleTypeIconFile</key>
-<string>Jalview-Launch.icns</string>
+<string>jvl_file.icns</string>
 <key>CFBundleTypeRole</key>
 <string>Editor</string>
 <key>CFBundleTypeMIMETypes</key>
index a4bdc49..b995078 100644 (file)
@@ -66,7 +66,7 @@
                       <property name="launcherId" type="string">JALVIEW</property>
                       <property name="macIconFile">
                         <object class="com.install4j.api.beans.ExternalFile">
-                          <string>Jalview-Launch.icns</string>
+                          <string>jvl_file.icns</string>
                         </object>
                       </property>
                       <property name="macRole" type="enum" class="com.install4j.runtime.beans.actions.desktop.MacAssociationRole" value="EDITOR" />
                       <property name="unix" type="boolean" value="true" />
                       <property name="unixIconFile">
                         <object class="com.install4j.api.beans.ExternalFile">
-                          <string>Jalview-Launch.png</string>
+                          <string>jvl_file.png</string>
                         </object>
                       </property>
                       <property name="unixMimeType" type="string">application/x-jalview-jvl+text</property>
                       <property name="windowsIconFile">
                         <object class="com.install4j.api.beans.ExternalFile">
-                          <string>Jalview-Launch.ico</string>
+                          <string>jvl_file.ico</string>
                         </object>
                       </property>
                     </serializedBean>
index b0828eb..e4e2193 100644 (file)
@@ -1287,7 +1287,7 @@ return console.askYesNo(message, true);
         <file name=".background/jalview_dmg_background.png" file="${compiler:JALVIEW_DIR}/${compiler:MACOS_DMG_BG_IMAGE}" />
         <file name=".DS_Store" file="${compiler:JALVIEW_DIR}/${compiler:MACOS_DMG_DS_STORE}" />
         <file name="${compiler:JALVIEW_APPLICATION_NAME}.app/Contents/Resources/Jalview-File.icns" file="${compiler:JALVIEW_DIR}/${compiler:INSTALL4J_UTILS_DIR}/Jalview-File.icns" />
-        <file name="${compiler:JALVIEW_APPLICATION_NAME}.app/Contents/Resources/Jalview-Launch.icns" file="${compiler:JALVIEW_DIR}/${compiler:INSTALL4J_UTILS_DIR}/Jalview-Launch.icns" />
+        <file name="${compiler:JALVIEW_APPLICATION_NAME}.app/Contents/Resources/jvl_file.icns" file="${compiler:JALVIEW_DIR}/${compiler:INSTALL4J_UTILS_DIR}/jvl_file.icns" />
         <symlink name="${compiler:JALVIEW_APPLICATION_NAME}.app/Contents/MacOS/${compiler:WRAPPER_LINK}" target="../Resources/app/${compiler:WRAPPER_SCRIPT_BIN_DIR}/${compiler:BASH_WRAPPER_SCRIPT}" />
       </topLevelFiles>
     </macosArchive>
diff --git a/utils/install4j/jvl_file.icns b/utils/install4j/jvl_file.icns
new file mode 100644 (file)
index 0000000..8230feb
Binary files /dev/null and b/utils/install4j/jvl_file.icns differ
diff --git a/utils/install4j/jvl_file.ico b/utils/install4j/jvl_file.ico
new file mode 100644 (file)
index 0000000..8811bc2
Binary files /dev/null and b/utils/install4j/jvl_file.ico differ
diff --git a/utils/install4j/jvl_file.png b/utils/install4j/jvl_file.png
new file mode 100644 (file)
index 0000000..56e9eae
Binary files /dev/null and b/utils/install4j/jvl_file.png differ
diff --git a/utils/install4j/jvl_file.svg b/utils/install4j/jvl_file.svg
new file mode 100644 (file)
index 0000000..c6e01be
--- /dev/null
@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   version="1.1"
+   id="Layer_1"
+   x="0px"
+   y="0px"
+   viewBox="0 0 85.33334 85.333347"
+   enable-background="new 0 0 595.238 595.238"
+   xml:space="preserve"
+   sodipodi:docname="jvl_file.svg"
+   width="85.333344"
+   height="85.333344"
+   inkscape:version="0.92.5 (2060ec1f9f, 2020-04-08)"><sodipodi:namedview
+   pagecolor="#ffffff"
+   bordercolor="#666666"
+   borderopacity="1"
+   objecttolerance="10"
+   gridtolerance="10"
+   guidetolerance="10"
+   inkscape:pageopacity="0"
+   inkscape:pageshadow="2"
+   inkscape:window-width="2152"
+   inkscape:window-height="1410"
+   id="namedview11"
+   showgrid="false"
+   fit-margin-top="0"
+   fit-margin-left="0"
+   fit-margin-right="0"
+   fit-margin-bottom="0"
+   inkscape:zoom="2.7754382"
+   inkscape:cx="42.666672"
+   inkscape:cy="42.515809"
+   inkscape:window-x="0"
+   inkscape:window-y="0"
+   inkscape:window-maximized="0"
+   inkscape:current-layer="Layer_1" />
+  <metadata
+   id="metadata41">
+    <rdf:RDF>
+      <cc:Work
+   rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+   rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title></dc:title>
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <defs
+   id="defs39">
+    
+    
+    
+    
+    
+    
+  </defs>
+  <g
+   id="g4756"
+   transform="translate(4.0769397e-6,-0.15086052)"><rect
+     style="fill:#0084a9;stroke-width:1"
+     id="rect2"
+     height="20.911402"
+     width="20.91173"
+     y="32.353989"
+     x="32.057495" /><path
+     inkscape:connector-curvature="0"
+     id="polygon4"
+     d="M 0,0.30172379 0.00572055,53.26261 H 10.525655 V 10.821168 H 68.897858 L 58.376942,0.30172379 Z"
+     style="fill:#ad208e;stroke-width:1" /><path
+     inkscape:connector-curvature="0"
+     id="polygon6"
+     d="m 26.699622,26.995298 h 31.67732 L 68.897858,16.921076 H 16.62115 v 36.329112 h 10.078472 z"
+     style="fill:#f78e1e;stroke-width:1" /><polygon
+     transform="matrix(0.16344439,0,0,0.16344439,-6.339681,-5.9678396)"
+     style="fill:#009ddc;stroke-width:6.11828899"
+     id="polygon8"
+     points="137.861,494.236 202.225,558.595 560.882,558.607 560.848,234.574 496.501,234.574 496.501,494.26 " /><polygon
+     transform="matrix(0.16344439,0,0,0.16344439,-6.339681,-5.9678396)"
+     style="fill:#c1d82f;stroke-width:6.11828899"
+     id="polygon10"
+     points="457.329,234.646 395.688,234.646 395.688,395.282 38.904,395.282 100.535,456.929 457.329,456.929 " /><path
+     inkscape:connector-curvature="0"
+     style="fill:none;stroke:#000000;stroke-width:0.1"
+     id="path32"
+     d="M 0.43525241,58.050222" /></g>
+</svg>
\ No newline at end of file