JAL-2316 Refactoring of functionality to provide urls to gui
authorkiramt <k.mourao@dundee.ac.uk>
Tue, 15 Nov 2016 14:20:12 +0000 (14:20 +0000)
committerkiramt <k.mourao@dundee.ac.uk>
Tue, 15 Nov 2016 14:20:12 +0000 (14:20 +0000)
13 files changed:
resources/lang/Messages.properties
resources/lang/Messages_es.properties
src/jalview/appletgui/IdPanel.java
src/jalview/gui/Desktop.java
src/jalview/gui/IdPanel.java
src/jalview/gui/Preferences.java
src/jalview/util/CustomUrlProvider.java
src/jalview/util/IdentifiersUrlProvider.java
src/jalview/util/UrlConstants.java
src/jalview/util/UrlLink.java
src/jalview/util/UrlProvider.java
src/jalview/util/UrlProviderI.java
src/jalview/util/UrlProviderImpl.java [new file with mode: 0644]

index 49a0456..7582568 100644 (file)
@@ -1272,3 +1272,5 @@ label.SEQUENCE_ID_no_longer_used = $SEQUENCE_ID$ is no longer used for DB access
 label.SEQUENCE_ID_for_DB_ACCESSION1 = Please review your URL links in the 'Connections' tab of the Preferences window:
 label.SEQUENCE_ID_for_DB_ACCESSION2 = URL links using '$SEQUENCE_ID$' for DB accessions now use '$DB_ACCESSION$'.
 label.do_not_display_again = Do not display this message again
+exception.url_cannot_have_miriam_id = {0} is a MIRIAM id and cannot be used as a custom url name
+exception.url_cannot_have_duplicate_id = {0} cannot be used as a label for more than one link
\ No newline at end of file
index 96c8ef2..f3d782c 100644 (file)
@@ -1272,4 +1272,6 @@ label.operation_failed = Operaci
 label.SEQUENCE_ID_no_longer_used = $SEQUENCE_ID$ no se utiliza más para accesiones DB
 label.SEQUENCE_ID_for_DB_ACCESSION1 = Por favor, revise sus URLs en la pestaña 'Conexiones' de la ventana de Preferencias:
 label.SEQUENCE_ID_for_DB_ACCESSION2 = URL enlaza usando '$SEQUENCE_ID$' para accesiones DB ahora usar '$DB_ACCESSION$'.
-label.do_not_display_again = No mostrar este mensaje de nuevo
\ No newline at end of file
+label.do_not_display_again = No mostrar este mensaje de nuevo
+exception.url_cannot_have_miriam_id = {0} is a MIRIAM id and cannot be used as a custom url name
+exception.url_cannot_have_duplicate_id = {0} cannot be used as a label for more than one link
\ No newline at end of file
index 182f20e..f8ea522 100755 (executable)
  */
 package jalview.appletgui;
 
-import static jalview.util.UrlConstants.EMBLEBI_STRING;
-import static jalview.util.UrlConstants.SRS_STRING;
-
 import jalview.datamodel.Sequence;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceGroup;
 import jalview.datamodel.SequenceI;
-import jalview.util.UrlLink;
+import jalview.util.UrlProvider;
+import jalview.util.UrlProviderI;
 import jalview.viewmodel.AlignmentViewport;
 
 import java.awt.BorderLayout;
@@ -36,6 +34,7 @@ import java.awt.event.InputEvent;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Vector;
 
@@ -55,7 +54,7 @@ public class IdPanel extends Panel implements MouseListener,
 
   boolean mouseDragging = false;
 
-  java.util.Vector links = new java.util.Vector();
+  UrlProviderI urlProvider = null;
 
   public IdPanel(AlignViewport av, AlignmentPanel parent)
   {
@@ -69,6 +68,9 @@ public class IdPanel extends Panel implements MouseListener,
 
     String label, url;
     // TODO: add in group link parameter
+
+    // make a list of label,url pairs
+    HashMap<String, String> urlList = new HashMap<String, String>();
     if (av.applet != null)
     {
       for (int i = 1; i < 10; i++)
@@ -76,26 +78,16 @@ public class IdPanel extends Panel implements MouseListener,
         label = av.applet.getParameter("linkLabel_" + i);
         url = av.applet.getParameter("linkURL_" + i);
 
-        if (label != null && url != null)
-        {
-          links.addElement(label + "|" + url);
-        }
-
+        urlList.put(label, url);
       }
-    }
-    {
-      // upgrade old SRS link
-      int srsPos = links.indexOf(SRS_STRING);
-      if (srsPos > -1)
+
+      if (!urlList.isEmpty())
       {
-        links.setElementAt(EMBLEBI_STRING, srsPos);
+        // set default as first entry in list
+        String defaultUrl = av.applet.getParameter("linkLabel_1");
+        urlProvider = new UrlProvider(defaultUrl, urlList);
       }
     }
-    if (links.size() < 1)
-    {
-      links = new java.util.Vector();
-      links.addElement(EMBLEBI_STRING);
-    }
   }
 
   Tooltip tooltip;
@@ -225,54 +217,55 @@ public class IdPanel extends Panel implements MouseListener,
       return;
     }
     String id = sq.getName();
+    String url = urlProvider.getDefaultUrl(id);
+    String target = urlProvider.getDefaultTarget(id);
 
-    String target = null;
-    String url = null;
-    int i = 0;
-    while (url == null && i < links.size())
-    {
-      // DEFAULT LINK IS FIRST IN THE LINK LIST
-      // BUT IF ITS A REGEX AND DOES NOT MATCH THE NEXT ONE WILL BE TRIED
-      url = links.elementAt(i++).toString();
-      jalview.util.UrlLink urlLink = null;
-      try
-      {
-        urlLink = new UrlLink(url);
-        target = urlLink.getTarget();
-      } catch (Exception foo)
-      {
-        System.err.println("Exception for URLLink '" + url + "'");
-        foo.printStackTrace();
-        url = null;
-        continue;
-      }
+    /*    String target = null;
+        String url = null;
+        int i = 0;
+        while (url == null && i < links.size())
+        {
+          // DEFAULT LINK IS FIRST IN THE LINK LIST
+          // BUT IF ITS A REGEX AND DOES NOT MATCH THE NEXT ONE WILL BE TRIED
+          url = links.elementAt(i++).toString();
+          jalview.util.UrlLink urlLink = null;
+          try
+          {
+            urlLink = new UrlLink(url);
+            target = urlLink.getTarget();
+          } catch (Exception foo)
+          {
+            System.err.println("Exception for URLLink '" + url + "'");
+            foo.printStackTrace();
+            url = null;
+            continue;
+          }
 
-      if (urlLink.usesDBAccession())
-      {
-        // this URL requires an accession id, not the name of a sequence
-        url = null;
-        continue;
-      }
+          if (urlLink.usesDBAccession())
+          {
+            // this URL requires an accession id, not the name of a sequence
+            url = null;
+            continue;
+          }
 
-      if (!urlLink.isValid())
-      {
-        System.err.println(urlLink.getInvalidMessage());
-        url = null;
-        continue;
-      }
+          if (!urlLink.isValid())
+          {
+            System.err.println(urlLink.getInvalidMessage());
+            url = null;
+            continue;
+          }
 
-      String urls[] = urlLink.makeUrls(id, true);
-      if (urls == null || urls[0] == null || urls[0].length() < 1)
-      {
-        url = null;
-        continue;
-      }
-      // just take first URL made from regex
-      url = urls[1];
-    }
+          String urls[] = urlLink.makeUrls(id, true);
+          if (urls == null || urls[0] == null || urls[0].length() < 1)
+          {
+            url = null;
+            continue;
+          }
+          // just take first URL made from regex
+          url = urls[1];
+        }*/
     try
     {
-
       alignPanel.alignFrame.showURL(url, target);
     } catch (Exception ex)
     {
@@ -331,11 +324,8 @@ public class IdPanel extends Panel implements MouseListener,
 
       // build a new links menu based on the current links + any non-positional
       // features
-      Vector nlinks = new Vector();
-      for (int l = 0, lSize = links.size(); l < lSize; l++)
-      {
-        nlinks.addElement(links.elementAt(l));
-      }
+      Vector<String> nlinks = urlProvider.getLinksForDisplay();
+
       SequenceFeature sf[] = sq == null ? null : sq.getSequenceFeatures();
       for (int sl = 0; sf != null && sl < sf.length; sl++)
       {
index 28606f1..63f797d 100644 (file)
@@ -20,7 +20,6 @@
  */
 package jalview.gui;
 
-import static jalview.util.UrlConstants.EMBLEBI_STRING;
 import static jalview.util.UrlConstants.SEQUENCE_ID;
 
 import jalview.api.AlignViewportI;
@@ -38,6 +37,7 @@ import jalview.structure.StructureSelectionManager;
 import jalview.util.ImageMaker;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
+import jalview.util.UrlProviderI;
 import jalview.viewmodel.AlignmentViewport;
 import jalview.ws.params.ParamManager;
 
@@ -2277,7 +2277,8 @@ public class Desktop extends jalview.jbgui.GDesktop implements
         {
           // check what the actual links are - if it's just the default don't
           // bother with the warning
-          Vector<String> links = Preferences.sequenceURLLinks;
+          Vector<String> links = Preferences.sequenceUrlLinks
+                  .getLinksForDisplay();
 
           // only need to check links if there is one with a
           // SEQUENCE_ID which is not the default EMBL_EBI link
@@ -2287,7 +2288,8 @@ public class Desktop extends jalview.jbgui.GDesktop implements
           while (li.hasNext())
           {
             String link = li.next();
-            if (link.contains(SEQUENCE_ID) && !link.equals(EMBLEBI_STRING))
+            if (link.contains(SEQUENCE_ID)
+                    && !link.equals(UrlProviderI.DEFAULT_STRING))
             {
               check = true;
               int barPos = link.indexOf("|");
index e321a74..7170d04 100755 (executable)
@@ -27,7 +27,6 @@ import jalview.datamodel.SequenceI;
 import jalview.io.SequenceAnnotationReport;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
-import jalview.util.UrlLink;
 import jalview.viewmodel.AlignmentViewport;
 
 import java.awt.BorderLayout;
@@ -199,56 +198,10 @@ public class IdPanel extends JPanel implements MouseListener,
       return;
     }
 
-    Vector links = Preferences.sequenceURLLinks;
-    if (links == null || links.size() < 1)
-    {
-      return;
-    }
-
     int seq = alignPanel.getSeqPanel().findSeq(e);
-    String url = null;
-    int i = 0;
     String id = av.getAlignment().getSequenceAt(seq).getName();
-    while (url == null && i < links.size())
-    {
-      // DEFAULT LINK IS FIRST IN THE LINK LIST
-      // BUT IF ITS A REGEX AND DOES NOT MATCH THE NEXT ONE WILL BE TRIED
-      url = links.elementAt(i++).toString();
-      jalview.util.UrlLink urlLink = null;
-      try
-      {
-        urlLink = new UrlLink(url);
-      } catch (Exception foo)
-      {
-        jalview.bin.Cache.log.error("Exception for URLLink '" + url + "'",
-                foo);
-        url = null;
-        continue;
-      }
+    String url = Preferences.sequenceUrlLinks.getDefaultUrl(id);
 
-      if (urlLink.usesDBAccession())
-      {
-        // this URL requires an accession id, not the name of a sequence
-        url = null;
-        continue;
-      }
-
-      if (!urlLink.isValid())
-      {
-        jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
-        url = null;
-        continue;
-      }
-
-      String urls[] = urlLink.makeUrls(id, true);
-      if (urls == null || urls[0] == null || urls[0].length() < 4)
-      {
-        url = null;
-        continue;
-      }
-      // just take first URL made from regex
-      url = urls[1];
-    }
     try
     {
       jalview.util.BrowserLauncher.openURL(url);
@@ -375,7 +328,9 @@ public class IdPanel extends JPanel implements MouseListener,
     Sequence sq = (Sequence) av.getAlignment().getSequenceAt(seq2);
     // build a new links menu based on the current links + any non-positional
     // features
-    Vector<String> nlinks = new Vector<String>(Preferences.sequenceURLLinks);
+    Vector<String> nlinks = Preferences.sequenceUrlLinks
+            .getLinksForDisplay(); // new
+                                   // Vector<String>(Preferences.sequenceURLLinks);
     SequenceFeature sfs[] = sq == null ? null : sq.getSequenceFeatures();
     if (sfs != null)
     {
index 718e14f..69dc9fe 100755 (executable)
@@ -20,8 +20,6 @@
  */
 package jalview.gui;
 
-import static jalview.util.UrlConstants.EMBLEBI_STRING;
-
 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
 import jalview.bin.Cache;
 import jalview.gui.Help.HelpId;
@@ -100,7 +98,6 @@ public class Preferences extends GPreferences
    * Holds name and link separated with | character. Sequence ID must be
    * $SEQUENCE_ID$ or $SEQUENCE_ID=/.possible | chars ./=$
    */
-  // public static Vector<String> sequenceURLLinks;
   public static UrlProviderI sequenceUrlLinks;
 
   /**
@@ -114,43 +111,10 @@ public class Preferences extends GPreferences
   public static List<String> groupURLLinks;
   static
   {
-    String string = Cache.getDefault("SEQUENCE_LINKS", EMBLEBI_STRING);
-    sequenceUrlLinks = new UrlProvider(EMBLEBI_STRING.split("\\|")[0],
-            string); // TODO sort out the default string
-    // sequenceURLLinks = new Vector<String>();
+    String string = Cache.getDefault("SEQUENCE_LINKS",
+            UrlProviderI.DEFAULT_STRING);
+    sequenceUrlLinks = new UrlProvider(UrlProviderI.DEFAULT_LABEL, string);
 
-    /*    try
-        {
-          StringTokenizer st = new StringTokenizer(string, "|");
-          while (st.hasMoreElements())
-          {
-            String name = st.nextToken();
-            String url = st.nextToken();
-            // check for '|' within a regex
-            int rxstart = url.indexOf("$" + DB_ACCESSION + "$");
-            if (rxstart == -1)
-            {
-              rxstart = url.indexOf("$" + SEQUENCE_ID + "$");
-            }
-            while (rxstart == -1 && url.indexOf("/=$") == -1)
-            {
-              url = url + "|" + st.nextToken();
-            }
-            sequenceURLLinks.addElement(name + "|" + url);
-          }
-        } catch (Exception ex)
-        {
-          System.out.println(ex + "\nError parsing sequence links");
-        }
-        {
-          // upgrade old SRS link
-          int srsPos = sequenceURLLinks.indexOf(SRS_STRING);
-          if (srsPos > -1)
-          {
-            sequenceURLLinks.setElementAt(EMBLEBI_STRING, srsPos);
-          }
-        }
-    */
     /**
      * TODO: reformulate groupURL encoding so two or more can be stored in the
      * .properties file as '|' separated strings
@@ -346,14 +310,8 @@ public class Preferences extends GPreferences
      */
     nameLinks = new Vector<String>();
     urlLinks = new Vector<String>();
-    sequenceUrlLinks.getLinksForDisplay(nameLinks, urlLinks);
-    /*    for (HashMap.Entry<String, UrlLink> entry: sequenceUrlLinks.getUrlLinks())
-        {
-          String link = sequenceURLLinks.elementAt(i).toString();
-          nameLinks.addElement(link.substring(0, link.indexOf("|")));
-          urlLinks.addElement(link.substring(link.indexOf("|") + 1));
-        }
-    */
+
+    resetStoredLinks();
     updateLinkData();
 
     useProxy.setSelected(Cache.getDefault("USE_PROXY", false));
@@ -550,6 +508,7 @@ public class Preferences extends GPreferences
 
     jalview.util.BrowserLauncher.resetBrowser();
 
+    // save user-defined and selected links
     String links = sequenceUrlLinks.writeUrlsAsString();
     if (links.isEmpty())
     {
@@ -561,28 +520,6 @@ public class Preferences extends GPreferences
               links.toString());
     }
 
-    /*    if (nameLinks.size() > 0)
-        {
-          StringBuffer links = new StringBuffer();
-          sequenceURLLinks = new Vector<String>();
-          for (int i = 0; i < nameLinks.size(); i++)
-          {
-            sequenceURLLinks.addElement(nameLinks.elementAt(i) + "|"
-                    + urlLinks.elementAt(i));
-            links.append(sequenceURLLinks.elementAt(i).toString());
-            links.append("|");
-          }
-          // remove last "|"
-          links.setLength(links.length() - 1);
-          Cache.applicationProperties.setProperty("SEQUENCE_LINKS",
-                  links.toString());
-        }
-        else
-        {
-          Cache.applicationProperties.remove("SEQUENCE_LINKS");
-          sequenceURLLinks.clear();
-        }*/
-
     Cache.applicationProperties.setProperty("USE_PROXY",
             Boolean.toString(useProxy.isSelected()));
 
@@ -775,8 +712,14 @@ public class Preferences extends GPreferences
         {
           nameLinks.addElement(link.getName());
           urlLinks.addElement(link.getURL());
-          updateLinkData();
-          valid = true;
+          if (updateLinkData())
+          {
+            valid = true;
+          }
+          else
+          {
+            break;
+          }
         }
       }
       else
@@ -816,8 +759,14 @@ public class Preferences extends GPreferences
         {
           nameLinks.setElementAt(link.getName(), index);
           urlLinks.setElementAt(link.getURL(), index);
-          updateLinkData();
-          valid = true;
+          if (updateLinkData())
+          {
+            valid = true;
+          }
+          else
+          {
+            break;
+          }
         }
       }
 
@@ -845,10 +794,42 @@ public class Preferences extends GPreferences
     updateLinkData();
   }
 
-  void updateLinkData()
+  private boolean updateLinkData()
+  {
+    try
+    {
+      sequenceUrlLinks.setUrlLinks(nameLinks, urlLinks);
+      linkNameList.setListData(nameLinks);
+      linkURLList.setListData(urlLinks);
+    } catch (IllegalArgumentException e)
+    {
+
+      // put back the old links
+      resetStoredLinks();
+
+      linkNameList.setListData(nameLinks);
+      linkURLList.setListData(urlLinks);
+
+      JOptionPane.showInternalMessageDialog(Desktop.desktop,
+              e.getMessage(), MessageManager.getString("label.link_name"),
+              JOptionPane.WARNING_MESSAGE);
+
+      return false;
+    }
+    return true;
+  }
+
+  private void resetStoredLinks()
   {
-    linkNameList.setListData(nameLinks);
-    linkURLList.setListData(urlLinks);
+    Vector<String> nlinks = sequenceUrlLinks.getLinksForDisplay();
+
+    nameLinks.clear();
+    urlLinks.clear();
+    for (String entry : nlinks)
+    {
+      nameLinks.addElement(entry.split("\\|")[0]);
+      urlLinks.addElement(entry.split("\\|")[1]);
+    }
   }
 
   @Override
index f679e36..e6f19fb 100644 (file)
 package jalview.util;
 
 import static jalview.util.UrlConstants.DB_ACCESSION;
-import static jalview.util.UrlConstants.EMBLEBI_STRING;
+import static jalview.util.UrlConstants.DELIM;
+//import static jalview.util.UrlConstants.EMBLEBI_LABEL;
+//import static jalview.util.UrlConstants.EMBLEBI_STRING;
+import static jalview.util.UrlConstants.SEP;
 import static jalview.util.UrlConstants.SEQUENCE_ID;
-import static jalview.util.UrlConstants.SRS_STRING;
+//import static jalview.util.UrlConstants.SRS_LABEL;
 
 import java.util.HashMap;
 import java.util.Iterator;
@@ -40,81 +43,118 @@ import java.util.Vector;
  * @author $author$
  * @version $Revision$
  */
-public class CustomUrlProvider implements UrlProviderI
+public class CustomUrlProvider extends UrlProviderImpl
 {
 
+  // minimum length of substitution in url link string
+  private static final int MIN_SUBST_LENGTH = 4;
+
+  // Default sequence URL link label for SRS
+  private static final String SRS_LABEL = "SRS";
+
+  // map of string ids to urlLinks
   private HashMap<String, UrlLink> urls;
 
+  /**
+   * Construct UrlProvider for custom (user-entered) URLs
+   * 
+   * @param cachedUrlList
+   *          list of URLs in form stored in Cache. i.e. SEP delimited string
+   */
   public CustomUrlProvider(String cachedUrlList)
   {
     try
     {
-      StringTokenizer st = new StringTokenizer(cachedUrlList, "|");
+      urls = new HashMap<String, UrlLink>();
+
+      // cachedUrlList is in form <label>|<url>|<label>|<url>...
+      // parse cachedUrlList into labels (used as id) and url links
+      StringTokenizer st = new StringTokenizer(cachedUrlList, SEP);
       while (st.hasMoreElements())
       {
         String name = st.nextToken();
         String url = st.nextToken();
         // check for '|' within a regex
-        int rxstart = url.indexOf("$" + DB_ACCESSION + "$");
+        int rxstart = url.indexOf(DELIM + DB_ACCESSION + DELIM);
         if (rxstart == -1)
         {
-          rxstart = url.indexOf("$" + SEQUENCE_ID + "$");
+          rxstart = url.indexOf(DELIM + SEQUENCE_ID + DELIM);
         }
-        while (rxstart == -1 && url.indexOf("/=$") == -1)
+        while (rxstart == -1 && url.indexOf("/=" + DELIM) == -1)
         {
-          url = url + "|" + st.nextToken();
+          url = url + SEP + st.nextToken();
         }
-        urls.put(name, new UrlLink(url));
-        // sequenceURLLinks.addElement(name + "|" + url);
+        urls.put(name, new UrlLink(name + SEP + url));
       }
     } catch (Exception ex)
     {
       System.out.println(ex + "\nError parsing sequence links");
     }
+    upgradeOldLinks();
 
-    // upgrade old SRS link
-    String srs_key = SRS_STRING.split("\\|")[0];
-    if (urls.containsKey(srs_key))
+  }
+
+  /**
+   * Construct UrlProvider for custom (user-entered) URLs
+   * 
+   * @param urlList
+   *          list of URLs as (label,url) pairs
+   */
+  public CustomUrlProvider(Map<String, String> urlList)
+  {
+    try
     {
-      urls.remove(srs_key);
-      urls.put(EMBLEBI_STRING.split("//|")[0],
-              new UrlLink(EMBLEBI_STRING.split("//|")[1]));
+      urls = new HashMap<String, UrlLink>();
+      Iterator<Map.Entry<String, String>> it = urlList.entrySet()
+              .iterator();
+      while (it.hasNext())
+      {
+        Map.Entry<String, String> pair = it.next();
+        urls.put(pair.getKey(),
+                new UrlLink(pair.getKey() + SEP + pair.getValue()));
+      }
+    } catch (Exception ex)
+    {
+      System.out.println(ex + "\nError parsing sequence links");
     }
+    upgradeOldLinks();
   }
 
-  @Override
-  public HashMap<String, UrlLink> getUrlLinks()
+  private void upgradeOldLinks()
   {
-    // TODO Auto-generated method stub
-    return null;
+    // upgrade old SRS link
+    if (urls.containsKey(SRS_LABEL))
+    {
+      urls.remove(SRS_LABEL);
+      urls.put(DEFAULT_LABEL, new UrlLink(DEFAULT_STRING));
+    }
   }
 
   @Override
-  public void getLinksForDisplay(Vector<String> nameLinks,
-          Vector<String> urlLinks)
+  public Vector<String> getLinksForDisplay()
   {
+    Vector<String> links = new Vector<String>();
     Iterator<Map.Entry<String, UrlLink>> it = urls.entrySet().iterator();
     while (it.hasNext())
     {
       Map.Entry<String, UrlLink> pair = it.next();
-      nameLinks.addElement(pair.getKey());
-      urlLinks.addElement(pair.getValue().toString()); // TODO check this is
-                                                       // right
+      links.add(pair.getValue().toString());
     }
+    return links;
   }
 
   @Override
-  public String getDefaultUrl()
-  {
-    // TODO Auto-generated method stub
-    return null;
-  }
-
-  @Override
-  public void setDefaultUrl(String id)
+  public boolean setDefaultUrl(String id)
   {
-    // TODO Auto-generated method stub
-
+    if (urls.containsKey(id))
+    {
+      defaultUrl = id;
+    }
+    else
+    {
+      defaultUrl = null;
+    }
+    return urls.containsKey(id);
   }
 
   @Override
@@ -126,10 +166,10 @@ public class CustomUrlProvider implements UrlProviderI
       for (UrlLink link : urls.values())
       {
         links.append(link.toString());
-        links.append("|");
+        links.append(SEP);
       }
 
-      // remove last "|"
+      // remove last SEP
       links.setLength(links.length() - 1);
     }
     else
@@ -140,18 +180,79 @@ public class CustomUrlProvider implements UrlProviderI
   }
 
   @Override
-  public void setUrlLinks(String cachedUrl)
+  public String getDefaultUrl(String seqid)
   {
-    // TODO Auto-generated method stub, maybe don't need this? watch out for
-    // superclass interactions
+    if (defaultUrl == null)
+    {
+      return null;
+    }
 
+    String url = null;
+    UrlLink urlLink = urls.get(defaultUrl);
+    String[] defaultUrls = urlLink.makeUrls(seqid, true);
+    if (defaultUrls == null || defaultUrls[0] == null
+            || defaultUrls[0].length() < MIN_SUBST_LENGTH)
+    {
+      url = null;
+    }
+    else
+    {
+      // just take first URL made from regex
+      url = defaultUrls[1];
+    }
+    return url;
   }
 
   @Override
-  public void setUrlLinks(HashMap<String, UrlLink> links)
+  public String getDefaultTarget(String seqid)
   {
-    // TODO Auto-generated method stub
+    return urls.get(defaultUrl).getTarget();
+  }
+
+  @Override
+  public void setUrlLinks(Vector<String> names, Vector<String> urlstrings)
+  {
+    HashMap<String, UrlLink> newurls = new HashMap<String, UrlLink>();
+
+    // should check that lists are same length but this function is likely
+    // to change once the Preferences dialog is rebuilt
+
+    for (int i = 0; i < names.size(); ++i)
+    {
+      // don't allow MIRIAM ids as custom url names (as the links will overwrite
+      // each other)
+      // unlikely user would try to do this, but...
+      if (isMiriamId(names.elementAt(i)))
+      {
+        throw new IllegalArgumentException(MessageManager.formatMessage(
+                "exception.url_cannot_have_miriam_id", names.elementAt(i)));
+      }
+      // don't allow duplicate key names as entries will be overwritten
+      if (newurls.containsKey(names.elementAt(i)))
+      {
+        throw new IllegalArgumentException(MessageManager.formatMessage(
+                "exception.url_cannot_have_duplicate_id",
+                names.elementAt(i)));
+      }
+      newurls.put(names.elementAt(i), new UrlLink(names.elementAt(i) + SEP
+              + urlstrings.elementAt(i)));
+    }
+
+    // don't update until we're sure this set is ok
+    urls = newurls;
 
   }
 
+  @Override
+  public String chooseDefaultUrl()
+  {
+    // unilaterally set the default id to the EMBL_EBI link
+    
+    if (!urls.containsKey(DEFAULT_LABEL))
+    {
+      urls.put(DEFAULT_LABEL, new UrlLink(DEFAULT_STRING));
+    }
+    return DEFAULT_LABEL;
+  }
+
 }
index e13eab5..6faf72d 100644 (file)
@@ -21,7 +21,7 @@
 
 package jalview.util;
 
-import java.util.HashMap;
+import java.util.Map;
 import java.util.Vector;
 
 /**
@@ -32,7 +32,7 @@ import java.util.Vector;
  * @author $author$
  * @version $Revision$
  */
-public class IdentifiersUrlProvider implements UrlProviderI
+public class IdentifiersUrlProvider extends UrlProviderImpl
 {
 
   public IdentifiersUrlProvider(String cachedUrlList)
@@ -40,11 +40,9 @@ public class IdentifiersUrlProvider implements UrlProviderI
 
   }
 
-  @Override
-  public HashMap<String, UrlLink> getUrlLinks()
+  public IdentifiersUrlProvider(Map<String, String> urlList)
   {
-    // TODO Auto-generated method stub
-    return null;
+
   }
 
   @Override
@@ -55,39 +53,50 @@ public class IdentifiersUrlProvider implements UrlProviderI
   }
 
   @Override
-  public void setDefaultUrl(String id)
+  public boolean setDefaultUrl(String id)
   {
-    // TODO Auto-generated method stub
-
+    return false;
   }
 
   @Override
   public String writeUrlsAsString()
   {
+    return "";
+  }
+
+  @Override
+  public Vector<String> getLinksForDisplay()
+  {
     // TODO Auto-generated method stub
     return null;
   }
 
   @Override
-  public void setUrlLinks(String cachedUrl)
+  public String getDefaultUrl(String seqid)
   {
     // TODO Auto-generated method stub
-
+    return null;
   }
 
   @Override
-  public void setUrlLinks(HashMap<String, UrlLink> links)
+  public String getDefaultTarget(String seqid)
   {
     // TODO Auto-generated method stub
+    return null;
+  }
 
+  @Override
+  public void setUrlLinks(Vector<String> names, Vector<String> urls)
+  {
+    // deliberately left empty
+    // TODO throw exception if called
   }
 
   @Override
-  public void getLinksForDisplay(Vector<String> nameLinks,
-          Vector<String> urlLinks)
+  public String chooseDefaultUrl()
   {
     // TODO Auto-generated method stub
-
+    return null;
   }
 
 }
index 1910bff..8b3f9b0 100644 (file)
@@ -37,14 +37,14 @@ public class UrlConstants
   public static final String SEQUENCE_ID = "SEQUENCE_ID";
 
   /*
-   * Default sequence URL link string for EMBL-EBI search
+   * Separator character used in Url links
    */
-  public static final String EMBLEBI_STRING = "EMBL-EBI Search|http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$SEQUENCE_ID$";
+  public static final String SEP = "|";
 
   /*
-   * Default sequence URL link string for SRS 
+   * Delimiter character used in Url links
    */
-  public static final String SRS_STRING = "SRS|http://srs.ebi.ac.uk/srsbin/cgi-bin/wgetz?-newId+(([uniprot-all:$SEQUENCE_ID$]))+-view+SwissEntry";
+  public static final String DELIM = "$";
 
   /*
    * not instantiable
index 3ee6432..c889287 100644 (file)
@@ -21,6 +21,8 @@
 package jalview.util;
 
 import static jalview.util.UrlConstants.DB_ACCESSION;
+import static jalview.util.UrlConstants.DELIM;
+import static jalview.util.UrlConstants.SEP;
 import static jalview.util.UrlConstants.SEQUENCE_ID;
 
 import jalview.datamodel.DBRefEntry;
@@ -43,11 +45,6 @@ public class UrlLink
    * documentation todo.
    */
 
-  // Internal constants
-  private static final String SEP = "|";
-
-  private static final String DELIM = "$";
-
   private String urlSuffix;
 
   private String urlPrefix;
index 3cd033b..f66e3fd 100644 (file)
@@ -21,8 +21,8 @@
 package jalview.util;
 
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.Vector;
 
 /**
@@ -37,70 +37,94 @@ public class UrlProvider implements UrlProviderI
   // List of actual URL link providers
   private List<UrlProviderI> providers;
 
-  // Record of default URL
-  private String defaultUrl;
-  
+  // Specific reference to custom URL link provider
+  private UrlProviderI customProvider;
+
   /**
    * Construct URL provider from string of cached URLs, and set default URL
    * 
-   * @param defaultUrl
+   * @param defaultUrlString
    *          id of the current default URL
    * @param cachedUrlList
    *          string listing current active URLs, expected to be custom URLs
    *          separated by |, or ids of URLs
    */
-  public UrlProvider(String defaultUrl, String cachedUrlList)
+  public UrlProvider(String defaultUrlString, String cachedUrlList)
   {
     // create all the UrlProviders we need
     providers = new ArrayList<UrlProviderI>();
     
     UrlProviderI idProvider = new IdentifiersUrlProvider(cachedUrlList);
-    UrlProviderI customProvider = new CustomUrlProvider(cachedUrlList);
+    customProvider = new CustomUrlProvider(cachedUrlList);
     providers.add(idProvider);
     providers.add(customProvider);
 
     // check that the defaultUrl still exists
+    if (!setDefaultUrl(defaultUrlString))
+    {
+      chooseDefaultUrl();
+    }
   }
   
   /**
-   * Get all the URL links
-   * @return all URL links
+   * Construct URL provider from a map of (label,url) pairs, and set default URL
+   * 
+   * @param defaultUrlString
+   *          id of the current default URL
+   * @param urlList
+   *          vector of (label, url) pairs
    */
-  @Override
-  public HashMap<String, UrlLink> getUrlLinks()
+  public UrlProvider(String defaultUrlString, Map<String, String> urlList)
   {
-    HashMap<String, UrlLink> urls = new HashMap<String, UrlLink>();
-    for (UrlProviderI p : providers)
+    // create all the UrlProviders we need
+    providers = new ArrayList<UrlProviderI>();
+
+    UrlProviderI idProvider = new IdentifiersUrlProvider(urlList);
+    customProvider = new CustomUrlProvider(urlList);
+    providers.add(idProvider);
+    providers.add(customProvider);
+
+    // check that the defaultUrl still exists
+    if (!setDefaultUrl(defaultUrlString))
     {
-      urls.putAll(p.getUrlLinks());
+      chooseDefaultUrl();
     }
-    return urls;
   }
-  
-  /**
-   * Get the default URL
-   * @return id of the default URL
-   */
+
   @Override
   public String getDefaultUrl()
   {
+    String defaultUrl = null;
+    for (UrlProviderI p : providers)
+    {
+      defaultUrl = p.getDefaultUrl();
+      if (defaultUrl != null)
+      {
+        return defaultUrl;
+      }
+    }
+
+    // no provider has a default set, just choose one
+    if (defaultUrl == null)
+    {
+      defaultUrl = chooseDefaultUrl();
+    }
     return defaultUrl;
   }
   
-  /**
-   * Set the default URL
-   * @param id the id of the URL to set as default
-   */
   @Override
-  public void setDefaultUrl(String id)
+  public boolean setDefaultUrl(String id)
   {
-    defaultUrl = id;
+    for (UrlProviderI p : providers)
+    {
+      if (p.setDefaultUrl(id))
+      {
+        return true;
+      }
+    }
+    return false;
   }
   
-  /**
-   * Write out all URLs as a string suitable for serialising
-   * @return string representation of available URLs
-   */
   @Override
   public String writeUrlsAsString()
   {
@@ -111,49 +135,74 @@ public class UrlProvider implements UrlProviderI
     }
     return result;
   }
-  
-  /**
-   * Set URL links from string
-   * 
-   * @param cachedUrl
-   *          string representation of URL links, i.e. | separated
-   */
+
   @Override
-  public void setUrlLinks(String cachedUrl)
+  public Vector<String> getLinksForDisplay()
   {
+    Vector<String> fullLinks = new Vector<String>();
     for (UrlProviderI p : providers)
     {
-      p.setUrlLinks(cachedUrl);
+      List<String> links = p.getLinksForDisplay();
+      if (links != null)
+      {
+        // will obliterate links with same keys from different providers
+        // must have checks in place to prevent user from duplicating ids
+        fullLinks.addAll(links);
+      }
     }
+    return fullLinks;
   }
-  
-  /**
-   * Set URL links from collection
-   * 
-   * @param links
-   *          hashmap containing string indexed UrlLinks
-   */
+
   @Override
-  public void setUrlLinks(HashMap<String, UrlLink> links)
+  public String getDefaultUrl(String seqid)
   {
+    String link = null;
     for (UrlProviderI p : providers)
     {
-      p.setUrlLinks(links);
+      if (p.getDefaultUrl(seqid) == null)
+      {
+        continue;
+      }
+      else
+      {
+        link = p.getDefaultUrl(seqid);
+        break;
+      }
     }
+    return link;
   }
 
   @Override
-  public void getLinksForDisplay(Vector<String> nameLinks,
-          Vector<String> urlLinks)
+  public String getDefaultTarget(String seqid)
   {
-    Vector<String> names = new Vector<String>();
-    Vector<String> links = new Vector<String>();
+    String target = null;
     for (UrlProviderI p : providers)
     {
-      p.getLinksForDisplay(names, links);
-      nameLinks.addAll(names);
-      urlLinks.addAll(links);
+      if (p.getDefaultTarget(seqid) == null)
+      {
+        continue;
+      }
+      else
+      {
+        target = p.getDefaultTarget(seqid);
+        break;
+      }
     }
+    return target;
+  }
+
+  @Override
+  public void setUrlLinks(Vector<String> names, Vector<String> urls)
+  {
+    // only allow custom urls to be updated by user
+    customProvider.setUrlLinks(names, urls);
   }
   
+  @Override
+  public String chooseDefaultUrl()
+  {
+    // choose a custom url default
+    return customProvider.chooseDefaultUrl();
+  }
+
 }
index 2118f7e..a0289e5 100644 (file)
@@ -20,7 +20,6 @@
  */
 package jalview.util;
 
-import java.util.HashMap;
 import java.util.Vector;
 
 /**
@@ -31,57 +30,77 @@ import java.util.Vector;
  */
 public interface UrlProviderI
 {
-  /**
-   * Get all the URL links
-   * 
-   * @return all URL links
+
+  /*
+   * Default sequence URL link label for EMBL-EBI search
    */
-  public HashMap<String, UrlLink> getUrlLinks();
+  public static final String DEFAULT_LABEL = "EMBL-EBI Search";
+
+  /*
+   * Default sequence URL link string for EMBL-EBI search
+   */
+  public static final String DEFAULT_STRING = DEFAULT_LABEL
+          + "|http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$SEQUENCE_ID$";
 
   /**
    * Get names and urls in as strings for display
    * 
-   * @param nameLinks
-   * @param urlLinks
    */
-  public void getLinksForDisplay(Vector<String> nameLinks,
-          Vector<String> urlLinks);
+  Vector<String> getLinksForDisplay();
 
   /**
-   * Get the default URL
+   * Get the id of the default URL
    * 
    * @return id of the default URL
    */
-  public String getDefaultUrl();
+  String getDefaultUrl();
+
+  /**
+   * Get the link for the default URL
+   * 
+   * @seqid sequence id for which to build link
+   * @return link for the default URL
+   */
+  String getDefaultUrl(String seqid);
+
+  /**
+   * Get the target of thelink for the default URL
+   * 
+   * @seqid sequence id for which to build link
+   * @return target of link for the default URL
+   */
+  String getDefaultTarget(String seqid);
 
   /**
    * Set the default URL
    * 
    * @param id
    *          the id of the URL to set as default
+   * @return true if setting was successful, false otherwise
    */
-  public void setDefaultUrl(String id);
+  boolean setDefaultUrl(String id);
 
   /**
    * Write out all URLs as a string suitable for serialising
    * 
    * @return string representation of available URLs
    */
-  public String writeUrlsAsString();
+  String writeUrlsAsString();
 
   /**
-   * Set URL links from string
+   * Set URL links from pair of collections
    * 
-   * @param cachedUrl
-   *          string representation of URL links, i.e. | separated
+   * @param names
+   * @param urls
    */
-  public void setUrlLinks(String cachedUrl);
+  void setUrlLinks(Vector<String> names, Vector<String> urls)
+          throws IllegalArgumentException;
 
   /**
-   * Set URL links from collection
+   * Choose the default URL in the event of the selected default being
+   * unavailable
    * 
-   * @param links
-   *          hashmap containing string indexed UrlLinks
+   * @return id of chosen default url
    */
-  public void setUrlLinks(HashMap<String, UrlLink> links);
+  String chooseDefaultUrl();
 }
diff --git a/src/jalview/util/UrlProviderImpl.java b/src/jalview/util/UrlProviderImpl.java
new file mode 100644 (file)
index 0000000..99f876c
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * 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.util.Vector;
+import java.util.regex.Pattern;
+
+public class UrlProviderImpl implements UrlProviderI
+{
+  private static final Pattern MIRIAM_PATTERN = Pattern
+          .compile("^MIR:\\d{8}$");
+  protected String defaultUrl;
+
+  @Override
+  public Vector<String> getLinksForDisplay()
+  {
+    // TODO Auto-generated method stub
+    return null;
+  }
+
+  @Override
+  public String getDefaultUrl()
+  {
+    return defaultUrl;
+  }
+
+  @Override
+  public String getDefaultUrl(String seqid)
+  {
+    // TODO Auto-generated method stub
+    return null;
+  }
+
+  @Override
+  public String getDefaultTarget(String seqid)
+  {
+    // TODO Auto-generated method stub
+    return null;
+  }
+
+  @Override
+  public boolean setDefaultUrl(String id)
+  {
+    // TODO Auto-generated method stub
+    return false;
+  }
+
+  @Override
+  public String writeUrlsAsString()
+  {
+    // TODO Auto-generated method stub
+    return null;
+  }
+
+  @Override
+  public void setUrlLinks(Vector<String> names, Vector<String> urls)
+  {
+    // TODO Auto-generated method stub
+
+  }
+
+  @Override
+  public String chooseDefaultUrl()
+  {
+    // TODO Auto-generated method stub
+    return null;
+  }
+
+  protected boolean isMiriamId(String id)
+  {
+    return MIRIAM_PATTERN.matcher(id).matches();
+  }
+
+
+
+}