JAL-3013 resolve symlink to hmmer binaries folder
[jalview.git] / src / jalview / hmmer / HmmerCommand.java
index 557598b..b5c1b25 100644 (file)
@@ -14,7 +14,9 @@ import jalview.gui.JvOptionPane;
 import jalview.gui.Preferences;
 import jalview.io.HMMFile;
 import jalview.io.StockholmFile;
+import jalview.util.FileUtils;
 import jalview.util.MessageManager;
+import jalview.util.Platform;
 import jalview.ws.params.ArgumentI;
 
 import java.io.BufferedReader;
@@ -22,6 +24,8 @@ import java.io.File;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.PrintWriter;
+import java.nio.file.Paths;
+import java.util.ArrayList;
 import java.util.Hashtable;
 import java.util.List;
 
@@ -31,25 +35,40 @@ import java.util.List;
  * @author TZVanaalten
  *
  */
-public class HmmerCommand
+public abstract class HmmerCommand implements Runnable
 {
   public static final String HMMBUILD = "hmmbuild";
 
-  private Hashtable hash = new Hashtable();
+  protected final AlignFrame af;
 
-  protected AlignFrame af;
+  protected final AlignmentI alignment;
 
-  protected List<ArgumentI> params;
+  protected final List<ArgumentI> params;
 
+  /**
+   * Constructor
+   * 
+   * @param alignFrame
+   * @param args
+   */
   public HmmerCommand(AlignFrame alignFrame, List<ArgumentI> args)
   {
     af = alignFrame;
+    alignment = af.getViewport().getAlignment();
     params = args;
   }
 
+  /**
+   * Answers true if preference HMMER_PATH is set, and its value is the path to
+   * a directory that contains an executable <code>hmmbuild</code> or
+   * <code>hmmbuild.exe</code>, else false
+   * 
+   * @return
+   */
   public static boolean isHmmerAvailable()
   {
-    File exec = getExecutable(HMMBUILD, Cache.getProperty(Preferences.HMMER_PATH));
+    File exec = FileUtils.getExecutable(HMMBUILD,
+            Cache.getProperty(Preferences.HMMER_PATH));
     return exec != null;
   }
 
@@ -59,35 +78,40 @@ public class HmmerCommand
    * 
    * @param seqs
    */
-  protected void stashSequences(SequenceI[] seqs)
+  protected Hashtable stashSequences(SequenceI[] seqs)
   {
-    hash = SeqsetUtils.uniquify(seqs, true);
+    return SeqsetUtils.uniquify(seqs, true);
   }
 
   /**
    * Restores the sequence data lost by uniquifying
    * 
+   * @param hashtable
    * @param seqs
    */
-  protected void recoverSequences(SequenceI[] seqs)
+  protected void recoverSequences(Hashtable hashtable, SequenceI[] seqs)
   {
-    SeqsetUtils.deuniquify(hash, seqs);
+    SeqsetUtils.deuniquify(hashtable, seqs);
   }
 
   /**
-   * Runs a command as a separate process
+   * Runs a command as a separate process and waits for it to complete. Answers
+   * true if the process return status is zero, else false.
    * 
-   * @param command
+   * @param commands
    *          the executable command and any arguments to it
    * @throws IOException
    */
-  public boolean runCommand(List<String> command)
+  public boolean runCommand(List<String> commands)
           throws IOException
   {
+    List<String> args = Platform.isWindows() ? wrapWithCygwin(commands)
+            : commands;
+
     try
     {
-      ProcessBuilder pb = new ProcessBuilder(command);
-      pb.redirectErrorStream(true); // send syserr to sysout
+      ProcessBuilder pb = new ProcessBuilder(args);
+      pb.redirectErrorStream(true); // merge syserr to sysout
       final Process p = pb.start();
       new Thread(new Runnable()
       {
@@ -112,7 +136,13 @@ public class HmmerCommand
       }).start();
 
       p.waitFor();
-      return p.exitValue() == 0; // 0 is success, by convention
+      int exitValue = p.exitValue();
+      if (exitValue != 0)
+      {
+        Cache.log.error("Command failed, return code = " + exitValue);
+        Cache.log.error("Command/args were: " + args.toString());
+      }
+      return exitValue == 0; // 0 is success, by convention
     } catch (Exception e)
     {
       e.printStackTrace();
@@ -121,8 +151,42 @@ public class HmmerCommand
   }
 
   /**
-   * Exports an alignment (and possibly annotation) to the specified file, in
-   * Stockholm format
+   * Converts the given command to a Cygwin "bash" command wrapper. The hmmer
+   * command and any arguments to it are converted into a single parameter to the
+   * bash command.
+   * 
+   * @param commands
+   */
+  protected List<String> wrapWithCygwin(List<String> commands)
+  {
+    File bash = FileUtils.getExecutable("bash",
+            Cache.getProperty(Preferences.CYGWIN_PATH));
+    if (bash == null)
+    {
+      Cache.log.error("Cygwin shell not found");
+      return commands;
+    }
+
+    List<String> wrapped = new ArrayList<>();
+    wrapped.add(bash.getAbsolutePath());
+    wrapped.add("-c");
+
+    /*
+     * combine hmmbuild/search/align and arguments to a single string
+     */
+    StringBuilder sb = new StringBuilder();
+    for (String cmd : commands)
+    {
+      sb.append(" ").append(cmd);
+    }
+    wrapped.add(sb.toString());
+
+    return wrapped;
+  }
+
+  /**
+   * Exports an alignment, and reference (RF) annotation if present, to the
+   * specified file, in Stockholm format
    * 
    * @param seqs
    * @param toFile
@@ -130,15 +194,24 @@ public class HmmerCommand
    * @throws IOException
    */
   public void exportStockholm(SequenceI[] seqs, File toFile,
-          AnnotatedCollectionI annotated)
-          throws IOException
+          AnnotatedCollectionI annotated) throws IOException
   {
-    if (seqs != null)
+    if (seqs == null)
+    {
+      return;
+    }
+    AlignmentI newAl = new Alignment(seqs);
+    if (!newAl.isAligned())
+    {
+      newAl.padGaps();
+    }
+
+    if (toFile != null && annotated != null)
     {
-      AlignmentI newAl = new Alignment(seqs);
-      if (toFile != null && annotated != null)
+      AlignmentAnnotation[] annots = annotated.getAlignmentAnnotation();
+      if (annots != null)
       {
-        for (AlignmentAnnotation annot : annotated.getAlignmentAnnotation())
+        for (AlignmentAnnotation annot : annots)
         {
           if (annot.label.contains("Reference") || "RF".equals(annot.label))
           {
@@ -159,13 +232,13 @@ public class HmmerCommand
           }
         }
       }
-
-      StockholmFile file = new StockholmFile(newAl);
-      String output = file.print(seqs, false);
-      PrintWriter writer = new PrintWriter(toFile);
-      writer.println(output);
-      writer.close();
     }
+
+    StockholmFile file = new StockholmFile(newAl);
+    String output = file.print(seqs, false);
+    PrintWriter writer = new PrintWriter(toFile);
+    writer.println(output);
+    writer.close();
   }
 
   /**
@@ -175,81 +248,91 @@ public class HmmerCommand
    * @param cmd
    *          command short name e.g. hmmalign
    * @return
+   * @throws IOException
    */
-  protected String getCommandPath(String cmd)
+  protected String getCommandPath(String cmd) throws IOException
   {
     String binariesFolder = Cache.getProperty(Preferences.HMMER_PATH);
-    File file = getExecutable(cmd, binariesFolder);
+    // ensure any symlink to the directory is resolved:
+    binariesFolder = Paths.get(binariesFolder).toRealPath().toString();
+    File file = FileUtils.getExecutable(cmd, binariesFolder);
     if (file == null && af != null)
     {
-        JvOptionPane.showInternalMessageDialog(af,
-                MessageManager.getString("warn.hmm_command_failed"));
+      JvOptionPane.showInternalMessageDialog(af, MessageManager
+              .formatMessage("label.executable_not_found", cmd));
     }
 
-    return file == null ? null : file.getAbsolutePath();
+    return file == null ? null : getFilePath(file);
   }
 
   /**
-   * Answers the executable file for the given hmmer command, or null if not
-   * found or not executable. The path to the executable is the command name
-   * prefixed by the hmmer binaries folder path, optionally with .exe appended.
+   * Exports an HMM to the specified file
    * 
-   * @param cmd
-   *          hmmer command short name, for example hmmbuild
-   * @param binaryPath
-   *          parent folder containing hmmer executables
-   * @return
+   * @param hmm
+   * @param hmmFile
+   * @throws IOException
    */
-  public static File getExecutable(String cmd, String binaryPath)
+  public void exportHmm(HiddenMarkovModel hmm, File hmmFile)
+          throws IOException
   {
-    File file = new File(binaryPath, cmd);
-    if (!file.canExecute())
+    if (hmm != null)
     {
-      file = new File(binaryPath, cmd + ".exe");
-      {
-        if (!file.canExecute())
-        {
-          file = null;
-        }
-      }
+      HMMFile file = new HMMFile(hmm);
+      PrintWriter writer = new PrintWriter(hmmFile);
+      writer.print(file.print());
+      writer.close();
     }
-    return file;
   }
 
   /**
-   * A convenience method to create a temporary file that is deleted on exit of
-   * the JVM
+   * Answers the HMM profile for the profile sequence the user selected (default
+   * is just the first HMM sequence in the alignment)
    * 
-   * @param prefix
-   * @param suffix
    * @return
-   * @throws IOException
    */
-  protected File createTempFile(String prefix, String suffix)
-          throws IOException
+  protected HiddenMarkovModel getHmmProfile()
   {
-    File f = File.createTempFile(prefix, suffix);
-    f.deleteOnExit();
-    return f;
-
+    String alignToParamName = MessageManager.getString("label.use_hmm");
+    for (ArgumentI arg : params)
+    {
+      String name = arg.getName();
+      if (name.equals(alignToParamName))
+      {
+        String seqName = arg.getValue();
+        SequenceI hmmSeq = alignment.findName(seqName);
+        if (hmmSeq.hasHMMProfile())
+        {
+          return hmmSeq.getHMM();
+        }
+      }
+    }
+    return null;
   }
 
   /**
-   * Exports an HMM to the specified file
+   * Answers an absolute path to the given file, in a format suitable for
+   * processing by a hmmer command. On a Windows platform, the native Windows file
+   * path is converted to Cygwin format, by replacing '\'with '/' and drive letter
+   * X with /cygdrive/x.
    * 
-   * @param hmm
-   * @param hmmFile
-   * @throws IOException
+   * @param resultFile
+   * @return
    */
-  public void exportHmm(HiddenMarkovModel hmm, File hmmFile)
-          throws IOException
+  protected String getFilePath(File resultFile)
   {
-    if (hmm != null)
+    String path = resultFile.getAbsolutePath();
+    if (Platform.isWindows())
     {
-      HMMFile file = new HMMFile(hmm);
-      PrintWriter writer = new PrintWriter(hmmFile);
-      writer.print(file.print());
-      writer.close();
+      // the first backslash escapes '\' for the regular expression argument
+      path = path.replaceAll("\\" + File.separator, "/");
+      int colon = path.indexOf(':');
+      if (colon > 0)
+      {
+        String drive = path.substring(0, colon);
+        path = path.replaceAll(drive + ":", "/cygdrive/" + drive);
+      }
     }
+
+    return path;
   }
 }