JAL-1925 update source version in license
[jalview.git] / src / jalview / bin / JalviewLite.java
index 9aa5735..e177a59 100644 (file)
@@ -1,6 +1,6 @@
 /*
- * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
- * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9.0b2)
+ * Copyright (C) 2015 The Jalview Authors
  * 
  * This file is part of Jalview.
  * 
@@ -45,8 +45,10 @@ import jalview.io.NewickFile;
 import jalview.javascript.JSFunctionExec;
 import jalview.javascript.JalviewLiteJsApi;
 import jalview.javascript.JsCallBack;
+import jalview.javascript.MouseOverStructureListener;
 import jalview.structure.SelectionListener;
 import jalview.structure.StructureSelectionManager;
+import jalview.util.HttpUtils;
 import jalview.util.MessageManager;
 
 import java.applet.Applet;
@@ -61,10 +63,9 @@ import java.awt.event.ActionEvent;
 import java.awt.event.WindowAdapter;
 import java.awt.event.WindowEvent;
 import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URL;
+import java.util.ArrayList;
 import java.util.Hashtable;
 import java.util.List;
 import java.util.StringTokenizer;
@@ -92,7 +93,7 @@ public class JalviewLite extends Applet implements
   }
 
   // /////////////////////////////////////////
-  // The following public methods maybe called
+  // The following public methods may be called
   // externally, eg via javascript in HTML page
   /*
    * (non-Javadoc)
@@ -956,11 +957,16 @@ public class JalviewLite extends Applet implements
     }
   }
 
-  /*
-   * (non-Javadoc)
-   * 
+  /**
+   * Callable from javascript to register a javascript function to pass events
+   * to a structure viewer.
+   *
+   * @param listener
+   *          the name of a javascript function
+   * @param modelSet
+   *          a token separated list of PDB file names listened for
    * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
-   * java.lang.String)
+   *      java.lang.String)
    */
   public void setStructureListener(String listener, String modelSet)
   {
@@ -974,8 +980,8 @@ public class JalviewLite extends Applet implements
         return;
       }
     }
-    jalview.javascript.MouseOverStructureListener mol = new jalview.javascript.MouseOverStructureListener(
-            this, listener, separatorListToArray(modelSet));
+    MouseOverStructureListener mol = new MouseOverStructureListener(this,
+            listener, separatorListToArray(modelSet));
     javascriptListeners.addElement(mol);
     StructureSelectionManager.getStructureSelectionManager(this)
             .addStructureViewerListener(mol);
@@ -1289,7 +1295,7 @@ public class JalviewLite extends Applet implements
     {
       builddate = "unknown";
       version = "test";
-      installation = "Webstart";
+      installation = "applet";
       java.net.URL url = JalviewLite.class
               .getResource("/.build_properties");
       if (url != null)
@@ -1345,9 +1351,10 @@ public class JalviewLite extends Applet implements
   /**
    * init method for Jalview Applet
    */
+  @Override
   public void init()
   {
-    // remove any handlers that might be hanging around from an earlier instance
+    debug = TRUE.equalsIgnoreCase(getParameter("debug"));
     try
     {
       if (debug)
@@ -1370,23 +1377,17 @@ public class JalviewLite extends Applet implements
         ex.printStackTrace();
       }
     }
-    /**
-     * turn on extra applet debugging
-     */
-    debug = TRUE.equalsIgnoreCase(getParameter("debug"));
+
     if (debug)
     {
-
       System.err.println("JalviewLite Version " + getVersion());
       System.err.println("Build Date : " + getBuildDate());
       System.err.println("Installation : " + getInstallation());
-
     }
     String externalsviewer = getParameter("externalstructureviewer");
     if (externalsviewer != null)
     {
-      useXtrnalSviewer = externalsviewer.trim().toLowerCase()
-              .equals(TRUE);
+      useXtrnalSviewer = externalsviewer.trim().toLowerCase().equals(TRUE);
     }
     /**
      * if true disable the check for jmol
@@ -1412,7 +1413,9 @@ public class JalviewLite extends Applet implements
       }
       else
       {
-        throw new Error(MessageManager.getString("error.invalid_separator_parameter"));
+        throw new Error(
+                MessageManager
+                        .getString("error.invalid_separator_parameter"));
       }
     }
     int r = 255;
@@ -1459,7 +1462,7 @@ public class JalviewLite extends Applet implements
         file = data.toString();
       }
     }
-    if (TRUE.equalsIgnoreCase(getParameter("enableSplitFrame")))
+    if (getDefaultParameter("enableSplitFrame", true))
     {
       file2 = getParameter("file2");
     }
@@ -1788,27 +1791,72 @@ public class JalviewLite extends Applet implements
      * update the protocol state variable for accessing the datasource located
      * by file.
      * 
-     * @param file
+     * @param path
      * @return possibly updated datasource string
      */
-    public String setProtocolState(String file)
+    public String resolveFileProtocol(String path)
     {
-      if (file.startsWith("PASTE"))
+      /*
+       * is it paste data?
+       */
+      if (path.startsWith("PASTE"))
       {
-        file = file.substring(5);
         protocol = AppletFormatAdapter.PASTE;
+        return path.substring(5);
       }
-      else if (inArchive(file))
+
+      /*
+       * is it a URL?
+       */
+      if (path.indexOf("://") != -1)
       {
-        protocol = AppletFormatAdapter.CLASSLOADER;
+        protocol = AppletFormatAdapter.URL;
+        return path;
       }
-      else
+
+      /*
+       * try relative to document root
+       */
+      URL documentBase = getDocumentBase();
+      String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
+      if (HttpUtils.isValidUrl(withDocBase))
+      {
+        if (debug)
+        {
+          System.err.println("Prepended document base '" + documentBase
+                  + "' to make: '" + withDocBase + "'");
+        }
+        protocol = AppletFormatAdapter.URL;
+        return withDocBase;
+      }
+
+      /*
+       * try relative to codebase (if different to document base)
+       */
+      URL codeBase = getCodeBase();
+      String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
+              codeBase);
+      if (!withCodeBase.equals(withDocBase)
+              && HttpUtils.isValidUrl(withCodeBase))
       {
-        file = addProtocol(file);
         protocol = AppletFormatAdapter.URL;
+        if (debug)
+        {
+          System.err.println("Prepended codebase '" + codeBase
+                  + "' to make: '" + withCodeBase + "'");
+        }
+        return withCodeBase;
+      }
+
+      /*
+       * try locating by classloader; try this last so files in the directory
+       * are resolved using document base
+       */
+      if (inArchive(path))
+      {
+        protocol = AppletFormatAdapter.CLASSLOADER;
       }
-      dbgMsg("Protocol identified as '" + protocol + "'");
-      return file;
+      return path;
     }
 
     public LoadingThread(String file, String file2, JalviewLite _applet)
@@ -1884,8 +1932,11 @@ public class JalviewLite extends Applet implements
       {
         AlignmentI al1 = af.viewport.getAlignment();
         AlignmentI al2 = af2.viewport.getAlignment();
-        if (AlignmentUtils.isMappable(al1, al2))
+        AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
+        AlignmentI prot = al1.isNucleotide() ? al2 : al1;
+        if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
         {
+          al2.alignAs(al1);
           SplitFrame sf = new SplitFrame(af, af2);
           sf.addToDisplay(embedded, JalviewLite.this);
           return;
@@ -1915,13 +1966,14 @@ public class JalviewLite extends Applet implements
       {
         return null;
       }
-      String resolvedFile = setProtocolState(fileParam);
+      String resolvedFile = resolveFileProtocol(fileParam);
       String format = new IdentifyFile().Identify(resolvedFile, protocol);
       dbgMsg("File identified as '" + format + "'");
       AlignmentI al = null;
       try
       {
-        al = new AppletFormatAdapter().readFile(resolvedFile, protocol, format);
+        al = new AppletFormatAdapter().readFile(resolvedFile, protocol,
+                format);
         if ((al != null) && (al.getHeight() > 0))
         {
           dbgMsg("Successfully loaded file.");
@@ -1939,13 +1991,13 @@ public class JalviewLite extends Applet implements
           if (protocol == AppletFormatAdapter.PASTE)
           {
             newAlignFrame.setTitle(MessageManager.formatMessage(
-                    "label.sequences_from", new Object[]
-                    { applet.getDocumentBase().toString() }));
+                    "label.sequences_from", new Object[] { applet
+                            .getDocumentBase().toString() }));
           }
 
           newAlignFrame.statusBar.setText(MessageManager.formatMessage(
-                  "label.successfully_loaded_file", new Object[]
-                  { resolvedFile }));
+                  "label.successfully_loaded_file",
+                  new Object[] { resolvedFile }));
 
           return newAlignFrame;
         }
@@ -2040,18 +2092,17 @@ public class JalviewLite extends Applet implements
             String sequence = applet.getParameter("PDBSEQ");
             if (sequence != null)
             {
-              seqs = new SequenceI[]
-              { matcher == null ? (Sequence) alignFrame.getAlignViewport()
-                      .getAlignment().findName(sequence) : matcher
-                      .findIdMatch(sequence) };
+              seqs = new SequenceI[] { matcher == null ? (Sequence) alignFrame
+                      .getAlignViewport().getAlignment().findName(sequence)
+                      : matcher.findIdMatch(sequence) };
             }
 
           }
           else
           {
             param = st.nextToken();
-            Vector tmp = new Vector();
-            Vector tmp2 = new Vector();
+            List<SequenceI> tmp = new ArrayList<SequenceI>();
+            List<String> tmp2 = new ArrayList<String>();
 
             while (st.hasMoreTokens())
             {
@@ -2060,39 +2111,22 @@ public class JalviewLite extends Applet implements
               if (st2.countTokens() > 1)
               {
                 // This is the chain
-                tmp2.addElement(st2.nextToken());
+                tmp2.add(st2.nextToken());
                 seqstring = st2.nextToken();
               }
-              tmp.addElement(matcher == null ? (Sequence) alignFrame
+              tmp.add(matcher == null ? (Sequence) alignFrame
                       .getAlignViewport().getAlignment()
                       .findName(seqstring) : matcher.findIdMatch(seqstring));
             }
 
-            seqs = new SequenceI[tmp.size()];
-            tmp.copyInto(seqs);
+            seqs = tmp.toArray(new SequenceI[tmp.size()]);
             if (tmp2.size() == tmp.size())
             {
-              chains = new String[tmp2.size()];
-              tmp2.copyInto(chains);
+              chains = tmp2.toArray(new String[tmp2.size()]);
             }
           }
-          param = setProtocolState(param);
-
-          if (// !jmolAvailable
-          // &&
-          protocol == AppletFormatAdapter.CLASSLOADER && !useXtrnalSviewer)
-          {
-            // Re: JAL-357 : the bug isn't a problem if we are using an
-            // external viewer!
-            // TODO: verify this Re:
-            // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
-            // This exception preserves the current behaviour where, even if
-            // the local pdb file was identified in the class loader
-            protocol = AppletFormatAdapter.URL; // this is probably NOT
-            // CORRECT!
-            param = addProtocol(param); //
-          }
-
+          param = resolveFileProtocol(param);
+          // TODO check JAL-357 for files in a jar (CLASSLOADER)
           pdb.setFile(param);
 
           if (seqs != null)
@@ -2125,8 +2159,8 @@ public class JalviewLite extends Applet implements
             }
             else
             {
-              pdbs.addElement(new Object[]
-              { pdb, seqs, chains, new String(protocol) });
+              pdbs.addElement(new Object[] { pdb, seqs, chains,
+                  new String(protocol) });
             }
           }
         }
@@ -2169,7 +2203,7 @@ public class JalviewLite extends Applet implements
       {
         try
         {
-          param = setProtocolState(param);
+          param = resolveFileProtocol(param);
           JPredFile predictions = new JPredFile(param, protocol);
           JnetAnnotationMaker.add_annotation(predictions,
                   alignFrame.viewport.getAlignment(), 0, false);
@@ -2204,7 +2238,7 @@ public class JalviewLite extends Applet implements
       String param = applet.getParameter("annotations");
       if (param != null)
       {
-        param = setProtocolState(param);
+        param = resolveFileProtocol(param);
 
         if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
                 param, protocol))
@@ -2257,7 +2291,7 @@ public class JalviewLite extends Applet implements
       param = applet.getParameter("features");
       if (param != null)
       {
-        param = setProtocolState(param);
+        param = resolveFileProtocol(param);
 
         result = alignFrame.parseFeaturesFile(param, protocol);
       }
@@ -2326,7 +2360,7 @@ public class JalviewLite extends Applet implements
       {
         try
         {
-          treeFile = setProtocolState(treeFile);
+          treeFile = resolveFileProtocol(treeFile);
           NewickFile fin = new NewickFile(treeFile, protocol);
           fin.parse();
 
@@ -2351,113 +2385,29 @@ public class JalviewLite extends Applet implements
     /**
      * Discovers whether the given file is in the Applet Archive
      * 
-     * @param file
+     * @param f
      *          String
      * @return boolean
      */
-    boolean inArchive(String file)
+    boolean inArchive(String f)
     {
       // This might throw a security exception in certain browsers
       // Netscape Communicator for instance.
       try
       {
-        boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
+        boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
         if (debug)
         {
-          System.err.println("Resource '" + file + "' was "
-                  + (rtn ? "" : "not") + " located by classloader.");
+          System.err.println("Resource '" + f + "' was "
+                  + (rtn ? "" : "not ") + "located by classloader.");
         }
         return rtn;
       } catch (Exception ex)
       {
-        System.out.println("Exception checking resources: " + file + " "
-                + ex);
+        System.out.println("Exception checking resources: " + f + " " + ex);
         return false;
       }
     }
-
-    /**
-     * If the file is not already in URL format, tries to locate it by resolving
-     * as a URL.
-     * 
-     * @param file
-     * @return
-     */
-    String addProtocol(final String file)
-    {
-      if (file.indexOf("://") == -1)
-      {
-        /*
-         * Try relative to document base
-         */
-        String url = applet.resolveUrlForLocalOrAbsolute(file,
-                getDocumentBase());
-        if (urlExists(url))
-        {
-          if (debug)
-          {
-            System.err.println("Prepended document base for resource: '"
-                    + file + "'");
-          }
-          return url;
-        }
-
-        /*
-         * Try relative to codebase
-         */
-        url = applet.resolveUrlForLocalOrAbsolute(file, getCodeBase());
-        if (urlExists(url))
-        {
-          if (debug)
-          {
-            System.err.println("Prepended codebase for resource: '" + file
-                    + "'");
-          }
-          return url;
-        }
-      }
-
-      /*
-       * Not resolved, leave unchanged
-       */
-      return file;
-    }
-
-    /**
-     * Returns true if an input stream can be opened on the specified URL, else
-     * false.
-     * 
-     * @param url
-     * @return
-     */
-    private boolean urlExists(String url)
-    {
-      InputStream is = null;
-      try
-      {
-        is = new URL(url).openStream();
-        if (is != null)
-        {
-          return true;
-        }
-      } catch (Exception x)
-      {
-        // ignore
-      } finally
-      {
-        if (is != null)
-        {
-          try
-          {
-            is.close();
-          } catch (IOException e)
-          {
-            // ignore
-          }
-        }
-      }
-      return false;
-    }
   }
 
   /**
@@ -2510,9 +2460,9 @@ public class JalviewLite extends Applet implements
    * @param separator
    * @return elements separated by separator
    */
-  public String[] separatorListToArray(String list, String separator)
+  public static String[] separatorListToArray(String list, String separator)
   {
-    // note separator local variable intentionally masks object field
+    // TODO use StringUtils version (slightly different...)
     int seplen = separator.length();
     if (list == null || list.equals("") || list.equals(separator))
     {
@@ -2578,8 +2528,9 @@ public class JalviewLite extends Applet implements
    * @param separator
    * @return concatenated string
    */
-  public String arrayToSeparatorList(String[] list, String separator)
+  public static String arrayToSeparatorList(String[] list, String separator)
   {
+    // TODO use StringUtils version
     StringBuffer v = new StringBuffer();
     if (list != null && list.length > 0)
     {
@@ -2736,7 +2687,7 @@ public class JalviewLite extends Applet implements
     {
       return def;
     }
-    if (stn.toLowerCase().equals(TRUE))
+    if (TRUE.equalsIgnoreCase(stn))
     {
       return true;
     }
@@ -2897,27 +2848,61 @@ public class JalviewLite extends Applet implements
    * form a complete URL given a path to a resource and a reference location on
    * the same server
    * 
-   * @param url
+   * @param targetPath
    *          - an absolute path on the same server as localref or a document
    *          located relative to localref
    * @param localref
    *          - a URL on the same server as url
    * @return a complete URL for the resource located by url
    */
-  private String resolveUrlForLocalOrAbsolute(String url, URL localref)
+  private String resolveUrlForLocalOrAbsolute(String targetPath,
+          URL localref)
   {
-    String codebase = localref.toString();
-    if (url.indexOf("/") == 0)
+    String resolvedPath = "";
+    if (targetPath.startsWith("/"))
     {
-      url = codebase.substring(0, codebase.length()
-              - localref.getFile().length())
-              + url;
+      String codebase = localref.toString();
+      String localfile = localref.getFile();
+      resolvedPath = codebase.substring(0,
+              codebase.length() - localfile.length())
+              + targetPath;
+      return resolvedPath;
+    }
+
+    /*
+     * get URL path and strip off any trailing file e.g.
+     * www.jalview.org/examples/index.html#applets?a=b is trimmed to
+     * www.jalview.org/examples/
+     */
+    String urlPath = localref.toString();
+    String directoryPath = urlPath;
+    int lastSeparator = directoryPath.lastIndexOf("/");
+    if (lastSeparator > 0)
+    {
+      directoryPath = directoryPath.substring(0, lastSeparator + 1);
+    }
+
+    if (targetPath.startsWith("/"))
+    {
+      /*
+       * construct absolute URL to a file on the server - this is not allowed?
+       */
+      // String localfile = localref.getFile();
+      // resolvedPath = urlPath.substring(0,
+      // urlPath.length() - localfile.length())
+      // + targetPath;
+      resolvedPath = directoryPath + targetPath.substring(1);
     }
     else
     {
-      url = localref + url;
+      resolvedPath = directoryPath + targetPath;
+    }
+    if (debug)
+    {
+      System.err.println("resolveUrlForLocalOrAbsolute returning "
+              + resolvedPath);
     }
-    return url;
+    return resolvedPath;
   }
 
   /**
@@ -2939,8 +2924,8 @@ public class JalviewLite extends Applet implements
         URL prepend;
         url = resolveUrlForLocalOrAbsolute(
                 url,
-                prepend = getDefaultParameter("resolvetocodebase", false) ? getDocumentBase()
-                        : getCodeBase());
+                prepend = getDefaultParameter("resolvetocodebase", false) ? getCodeBase()
+                        : getDocumentBase());
         if (debug)
         {
           System.err