JAL-3725 helper methods for computing mapped feature range overlap
[jalview.git] / src / jalview / urls / IdentifiersUrlProvider.java
index 7819136..0988e7d 100644 (file)
@@ -25,17 +25,16 @@ import static jalview.util.UrlConstants.DB_ACCESSION;
 import static jalview.util.UrlConstants.DELIM;
 import static jalview.util.UrlConstants.SEP;
 
-import java.io.BufferedInputStream;
-import java.io.File;
+import jalview.util.UrlLink;
+
 import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Vector;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
 
 import org.json.simple.JSONArray;
 import org.json.simple.JSONObject;
@@ -53,181 +52,217 @@ import org.json.simple.parser.ParseException;
 public class IdentifiersUrlProvider extends UrlProviderImpl
 {
 
+  private static final String LOCAL_KEY = "Local";
+
+  private static final String ID_ORG_KEY = "identifiers.org";
+
   // map of string ids to urls
-  private HashMap<String, HashMap<String, String>> urls;
+  private HashMap<String, UrlLink> urls;
 
   // list of selected urls
   private ArrayList<String> selectedUrls;
 
-  public IdentifiersUrlProvider(String cachedUrlList, String idFileName)
-  {
-    try
-    {
-      // File idFile = getIdentifiers();
-      urls = readIdentifiers(new FileReader(idFileName));
-      checkSelectionMatchesUrls(cachedUrlList);
-
-    } catch (IOException e)
-    {
-
-    }
-  }
-
-  private File getIdentifiers() throws IOException
+  public IdentifiersUrlProvider(String cachedUrlList)
   {
-    String identifiersorgUrl = "http://identifiers.org/rest/collections/";
-    String outfile = "identifiers.json";
-    int BUFFER_SIZE = 4096;
-    
-    URL url = new URL(identifiersorgUrl);
-    InputStream is = new BufferedInputStream(url.openStream());
-    FileOutputStream os = new FileOutputStream(outfile);
-    byte[] buffer = new byte[BUFFER_SIZE];
-    int bytesRead = -1;
-    while ((bytesRead = is.read(buffer)) != -1)
-    {
-      os.write(buffer, 0, bytesRead);
-    }
-    os.close();
-    is.close();
-    
-    return new File(outfile);
+    urls = readIdentifiers(IdOrgSettings.getDownloadLocation());
+    selectedUrls = new ArrayList<String>();
+    checkSelectionMatchesUrls(cachedUrlList);
   }
 
-  private HashMap<String, HashMap<String, String>> readIdentifiers(
-          FileReader reader)
+  /**
+   * Read data from an identifiers.org download file
+   * 
+   * @param idFileName
+   *          name of identifiers.org download file
+   * @return hashmap of identifiers.org data, keyed by MIRIAM id
+   */
+  private HashMap<String, UrlLink> readIdentifiers(String idFileName)
   {
     JSONParser parser = new JSONParser();
-    HashMap<String, HashMap<String, String>> idData = new HashMap<String, HashMap<String, String>>();
+
+    // identifiers.org data
+    HashMap<String, UrlLink> idData = new HashMap<String, UrlLink>();
 
     try
     {
-      JSONArray jsonarray = (JSONArray) parser.parse(reader);
+      FileReader reader = new FileReader(idFileName);
+      String key = "";
+      JSONObject obj = (JSONObject) parser.parse(reader);
+      if (obj.containsKey(ID_ORG_KEY))
+      {
+        key = ID_ORG_KEY;
+      }
+      else if (obj.containsKey(LOCAL_KEY))
+      {
+        key = LOCAL_KEY;
+      }
+      else
+      {
+        System.out.println(
+                "Unexpected key returned from identifiers jalview service");
+        return idData;
+      }
+
+      JSONArray jsonarray = (JSONArray) obj.get(key);
 
       // loop over each entry in JSON array and build HashMap entry
       for (int i = 0; i < jsonarray.size(); i++)
       {
         JSONObject item = (JSONObject) jsonarray.get(i);
 
-        HashMap<String, String> idEntry = new HashMap<String, String>();
-        idEntry.put("name", (String) item.get("name"));
-        idEntry.put("url", (String) item.get("url"));
-        idData.put((String) item.get("id"), idEntry);
+        String url = (String) item.get("url") + "/" + DELIM + DB_ACCESSION
+                + DELIM;
+        UrlLink link = new UrlLink((String) item.get("name"), url,
+                (String) item.get("prefix"));
+        idData.put((String) item.get("id"), link);
       }
     } catch (FileNotFoundException e)
     {
       e.printStackTrace();
+      idData.clear();
     } catch (IOException e)
     {
       e.printStackTrace();
+      idData.clear();
     } catch (ParseException e)
     {
       e.printStackTrace();
+      idData.clear();
     }
     return idData;
   }
 
   private void checkSelectionMatchesUrls(String cachedUrlList)
   {
-    selectedUrls = new ArrayList<String>();
-    String[] prevSelected = cachedUrlList.split("\\" + SEP);
-    for (String id : prevSelected)
+    StringTokenizer st = new StringTokenizer(cachedUrlList, SEP);
+    while (st.hasMoreElements())
     {
-      if (urls.containsKey(id))
-      {
-        selectedUrls.add(id);
-      }
-    }
+      String id = st.nextToken();
 
-    // reset defaultUrl in case it is no longer selected
-    setDefaultUrl(defaultUrl);
-  }
-
-  private void checkSelectionMatchesUrls(Vector<String> idList)
-  {
-    selectedUrls = new ArrayList<String>();
-    String[] prevSelected = new String[idList.size()];
-    idList.toArray(prevSelected);
-    for (String id : prevSelected)
-    {
-      if (urls.containsKey(id))
+      if (isMiriamId(id))
       {
-        selectedUrls.add(id);
+        // this is an identifiers.org MIRIAM id
+        if (urls.containsKey(id))
+        {
+          selectedUrls.add(id);
+        }
       }
     }
 
     // reset defaultUrl in case it is no longer selected
-    setDefaultUrl(defaultUrl);
-  }
-
-  @Override
-  public String getDefaultUrl()
-  {
-    return defaultUrl;
+    setPrimaryUrl(primaryUrl);
   }
 
   @Override
-  public boolean setDefaultUrl(String id)
+  public boolean setPrimaryUrl(String id)
   {
-    if (selectedUrls.contains(id))
+    if (urls.containsKey(id))
     {
-      defaultUrl = id;
+      primaryUrl = id;
     }
     else
     {
-      defaultUrl = null;
+      primaryUrl = null;
     }
-    return selectedUrls.contains(id);
+
+    return urls.containsKey(id);
   }
 
   @Override
-  public String writeUrlsAsString()
+  public String writeUrlsAsString(boolean selected)
   {
+    if (!selected)
+    {
+      return ""; // we don't cache unselected identifiers.org urls
+    }
+
     StringBuffer links = new StringBuffer();
-    for (String k : selectedUrls)
+    if (!selectedUrls.isEmpty())
     {
-      links.append(k);
+      for (String k : selectedUrls)
+      {
+        links.append(k);
+        links.append(SEP);
+      }
+      // remove last SEP
+      links.setLength(links.length() - 1);
     }
     return links.toString();
   }
 
   @Override
-  public Vector<String> getLinksForDisplay()
+  public List<String> getLinksForMenu()
   {
-    Vector<String> links = new Vector<String>();
+    List<String> links = new ArrayList<String>();
     for (String key : selectedUrls)
     {
-      links.add(key + SEP + urls.get(key).get("url") + "/" + DELIM
-              + DB_ACCESSION + DELIM);
+      links.add(urls.get(key).toStringWithTarget());
     }
     return links;
   }
 
   @Override
-  public String getDefaultUrl(String seqid)
+  public List<UrlLinkDisplay> getLinksForTable()
   {
-    return urls.get(defaultUrl).get("url") + "/" + seqid;
+    return super.getLinksForTable(urls, selectedUrls, false);
   }
 
   @Override
-  public String getDefaultTarget(String seqid)
+  public void setUrlData(List<UrlLinkDisplay> links)
   {
-    // TODO Auto-generated method stub
-    return null;
+    selectedUrls = new ArrayList<String>();
+
+    Iterator<UrlLinkDisplay> it = links.iterator();
+    while (it.hasNext())
+    {
+      UrlLinkDisplay link = it.next();
+
+      // Handle links with MIRIAM ids only
+      if (isMiriamId(link.getId()))
+      {
+        // select/deselect links accordingly and set default url
+        if (urls.containsKey(link.getId()))
+        {
+          if (link.getIsSelected())
+          {
+            selectedUrls.add(link.getId());
+          }
+          if (link.getIsPrimary())
+          {
+            setPrimaryUrl(link.getId());
+          }
+        }
+      }
+    }
+  }
+
+  @Override
+  public String getPrimaryUrl(String seqid)
+  {
+    return super.getPrimaryUrl(seqid, urls);
   }
 
   @Override
-  public void setUrlLinks(Vector<String> names, Vector<String> urls)
+  public String getPrimaryUrlId()
   {
-    // ignores urls, only uses names (as ids)
-    checkSelectionMatchesUrls(names);
+    return primaryUrl;
   }
 
   @Override
-  public String chooseDefaultUrl()
+  public String getPrimaryTarget(String seqid)
   {
-    // TODO Auto-generated method stub
     return null;
   }
 
+  @Override
+  public String choosePrimaryUrl()
+  {
+    return null;
+  }
+
+  @Override
+  public boolean contains(String id)
+  {
+    return (urls.containsKey(id));
+  }
 }