JAL-2664 Updates following review
[jalview.git] / src / jalview / urls / IdentifiersUrlProvider.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21
22 package jalview.urls;
23
24 import static jalview.util.UrlConstants.DB_ACCESSION;
25 import static jalview.util.UrlConstants.DELIM;
26 import static jalview.util.UrlConstants.SEP;
27
28 import jalview.util.UrlLink;
29
30 import java.io.FileNotFoundException;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.StringTokenizer;
38
39 import org.json.simple.JSONArray;
40 import org.json.simple.JSONObject;
41 import org.json.simple.parser.JSONParser;
42 import org.json.simple.parser.ParseException;
43
44 /**
45  * 
46  * Implements the UrlProviderI interface for a UrlProvider object which serves
47  * URLs from identifiers.org
48  * 
49  * @author $author$
50  * @version $Revision$
51  */
52 public class IdentifiersUrlProvider extends UrlProviderImpl
53 {
54
55   private static final String LOCAL_KEY = "Local";
56
57   private static final String ID_ORG_KEY = "identifiers.org";
58
59   // map of string ids to urls
60   private HashMap<String, UrlLink> urls;
61
62   // list of selected urls
63   private ArrayList<String> selectedUrls;
64
65   public IdentifiersUrlProvider(String cachedUrlList)
66   {
67     urls = readIdentifiers(IdOrgSettings.getDownloadLocation());
68     selectedUrls = new ArrayList<String>();
69     checkSelectionMatchesUrls(cachedUrlList);
70   }
71
72   /**
73    * Read data from an identifiers.org download file
74    * 
75    * @param idFileName
76    *          name of identifiers.org download file
77    * @return hashmap of identifiers.org data, keyed by MIRIAM id
78    */
79   private HashMap<String, UrlLink> readIdentifiers(
80           String idFileName)
81   {
82     JSONParser parser = new JSONParser();
83
84     // identifiers.org data
85     HashMap<String, UrlLink> idData = new HashMap<String, UrlLink>();
86
87     try
88     {
89       FileReader reader = new FileReader(idFileName);
90       String key = "";
91       JSONObject obj = (JSONObject) parser.parse(reader);
92       if (obj.containsKey(ID_ORG_KEY))
93       {
94         key = ID_ORG_KEY;
95       }
96       else if (obj.containsKey(LOCAL_KEY))
97       {
98         key = LOCAL_KEY;
99       }
100       else
101       {
102         System.out
103                 .println("Unexpected key returned from identifiers jalview service");
104         return idData;
105       }
106
107       JSONArray jsonarray = (JSONArray) obj.get(key);
108
109       // loop over each entry in JSON array and build HashMap entry
110       for (int i = 0; i < jsonarray.size(); i++)
111       {
112         JSONObject item = (JSONObject) jsonarray.get(i);
113
114         String url = (String) item.get("url") + "/" + DELIM + DB_ACCESSION
115                 + DELIM;
116         UrlLink link = new UrlLink((String) item.get("name"), url,
117                 (String) item.get("prefix"));
118         idData.put((String) item.get("id"), link);
119       }
120     } catch (FileNotFoundException e)
121     {
122       e.printStackTrace();
123       idData.clear();
124     } catch (IOException e)
125     {
126       e.printStackTrace();
127       idData.clear();
128     } catch (ParseException e)
129     {
130       e.printStackTrace();
131       idData.clear();
132     }
133     return idData;
134   }
135
136   private void checkSelectionMatchesUrls(String cachedUrlList)
137   {
138     StringTokenizer st = new StringTokenizer(cachedUrlList, SEP);
139     while (st.hasMoreElements())
140     {
141       String id = st.nextToken();
142
143       if (isMiriamId(id))
144       {
145         // this is an identifiers.org MIRIAM id
146         if (urls.containsKey(id))
147         {
148           selectedUrls.add(id);
149         }
150       }
151     }
152
153     // reset defaultUrl in case it is no longer selected
154     setPrimaryUrl(primaryUrl);
155   }
156
157   @Override
158   public boolean setPrimaryUrl(String id)
159   {
160     if (urls.containsKey(id))
161     {
162       primaryUrl = id;
163     }
164     else
165     {
166       primaryUrl = null;
167     }
168
169     return urls.containsKey(id);
170   }
171
172   @Override
173   public String writeUrlsAsString(boolean selected)
174   {
175     if (!selected)
176     {
177       return ""; // we don't cache unselected identifiers.org urls
178     }
179
180     StringBuffer links = new StringBuffer();
181     if (!selectedUrls.isEmpty())
182     {
183       for (String k : selectedUrls)
184       {
185         links.append(k);
186         links.append(SEP);
187       }
188       // remove last SEP
189       links.setLength(links.length() - 1);
190     }
191     return links.toString();
192   }
193
194   @Override
195   public List<String> getLinksForMenu()
196   {
197     List<String> links = new ArrayList<String>();
198     for (String key : selectedUrls)
199     {
200       links.add(urls.get(key).toStringWithTarget());
201     }
202     return links;
203   }
204
205   @Override
206   public List<UrlLinkDisplay> getLinksForTable()
207   {
208     return super.getLinksForTable(urls, selectedUrls, false);
209   }
210
211   @Override
212   public void setUrlData(List<UrlLinkDisplay> links)
213   {
214     selectedUrls = new ArrayList<String>();
215
216     Iterator<UrlLinkDisplay> it = links.iterator();
217     while (it.hasNext())
218     {
219       UrlLinkDisplay link = it.next();
220
221       // Handle links with MIRIAM ids only
222       if (isMiriamId(link.getId()))
223       {
224         // select/deselect links accordingly and set default url
225         if (urls.containsKey(link.getId()))
226         {
227           if (link.getIsSelected())
228           {
229             selectedUrls.add(link.getId());
230           }
231           if (link.getIsPrimary())
232           {
233             setPrimaryUrl(link.getId());
234           }
235         }
236       }
237     }
238   }
239
240   @Override
241   public String getPrimaryUrl(String seqid)
242   {
243     return super.getPrimaryUrl(seqid, urls);
244   }
245
246   @Override
247   public String getPrimaryUrlId()
248   {
249     return primaryUrl;
250   }
251
252   @Override
253   public String getPrimaryTarget(String seqid)
254   {
255     return null;
256   }
257
258   @Override
259   public String choosePrimaryUrl()
260   {
261     return null;
262   }
263
264   @Override
265   public boolean contains(String id)
266   {
267     return (urls.containsKey(id));
268   }
269 }