b43db572be28483b12ea049fa6db24cf3b76c0f3
[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.JSONUtils;
29 import jalview.util.UrlLink;
30
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.Map;
38 import java.util.StringTokenizer;
39
40 import org.json.simple.parser.ParseException;
41
42 /**
43  * 
44  * Implements the UrlProviderI interface for a UrlProvider object which serves
45  * URLs from identifiers.org
46  * 
47  * @author $author$
48  * @version $Revision$
49  */
50 public class IdentifiersUrlProvider extends UrlProviderImpl
51 {
52
53   private static final String LOCAL_KEY = "Local";
54
55   private static final String ID_ORG_KEY = "identifiers.org";
56
57   // map of string ids to urls
58   private HashMap<String, UrlLink> urls;
59
60   // list of selected urls
61   private ArrayList<String> selectedUrls;
62
63   public IdentifiersUrlProvider(String cachedUrlList)
64   {
65     urls = readIdentifiers(IdOrgSettings.getDownloadLocation());
66     selectedUrls = new ArrayList<>();
67     checkSelectionMatchesUrls(cachedUrlList);
68   }
69
70   /**
71    * Read data from an identifiers.org download file
72    * 
73    * @param idFileName
74    *          name of identifiers.org download file
75    * @return hashmap of identifiers.org data, keyed by MIRIAM id
76    */
77   @SuppressWarnings("unchecked")
78 private HashMap<String, UrlLink> readIdentifiers(String idFileName)
79   {
80     // identifiers.org data
81     HashMap<String, UrlLink> idData = new HashMap<>();
82
83     String errorMessage = null;
84     try
85     {
86         // NOTE: THIS WILL FAIL IN SWINGJS BECAUSE IT INVOLVES A FILE READER
87     
88      // System.out.println("IDentifiersURLProvider.idFileName=" + idFileName);
89       FileReader reader = new FileReader(idFileName);
90       String key = "";
91       Map<String, Object> obj = (Map<String, Object>) JSONUtils.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.println(
103                 "Unexpected key returned from identifiers jalview service");
104         return idData;
105       }
106
107       List<Object> jsonarray = (List<Object>) 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         Map<String, Object> item = (Map<String, Object>) 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 (IOException | ParseException e)
121     {
122       //e.printStackTrace();
123       // Note how in JavaScript we can grab the first bytes from any file reader. 
124       // Typical report here is "NetworkError" because the file does not exist.
125       // "https://." is coming from System.getProperty("user.home"), but this could
126       // be set by the page developer to anything, of course.
127       errorMessage = e.toString();
128       idData.clear();
129     }
130     // BH 2018 -- added more valuable report
131     if (errorMessage != null)
132     {
133       System.err.println("IdentifiersUrlProvider: cannot read " + idFileName + ": " + errorMessage);
134     }
135     return idData;
136   }
137
138   private void checkSelectionMatchesUrls(String cachedUrlList)
139   {
140     StringTokenizer st = new StringTokenizer(cachedUrlList, SEP);
141     while (st.hasMoreElements())
142     {
143       String id = st.nextToken();
144
145       if (isMiriamId(id))
146       {
147         // this is an identifiers.org MIRIAM id
148         if (urls.containsKey(id))
149         {
150           selectedUrls.add(id);
151         }
152       }
153     }
154
155     // reset defaultUrl in case it is no longer selected
156     setPrimaryUrl(primaryUrl);
157   }
158
159   @Override
160   public boolean setPrimaryUrl(String id)
161   {
162     if (urls.containsKey(id))
163     {
164       primaryUrl = id;
165     }
166     else
167     {
168       primaryUrl = null;
169     }
170
171     return urls.containsKey(id);
172   }
173
174   @Override
175   public String writeUrlsAsString(boolean selected)
176   {
177     if (!selected)
178     {
179       return ""; // we don't cache unselected identifiers.org urls
180     }
181
182     StringBuffer links = new StringBuffer();
183     if (!selectedUrls.isEmpty())
184     {
185       for (String k : selectedUrls)
186       {
187         links.append(k);
188         links.append(SEP);
189       }
190       // remove last SEP
191       links.setLength(links.length() - 1);
192     }
193     return links.toString();
194   }
195
196   @Override
197   public List<String> getLinksForMenu()
198   {
199     List<String> links = new ArrayList<>();
200     for (String key : selectedUrls)
201     {
202       links.add(urls.get(key).toStringWithTarget());
203     }
204     return links;
205   }
206
207   @Override
208   public List<UrlLinkDisplay> getLinksForTable()
209   {
210     return super.getLinksForTable(urls, selectedUrls, false);
211   }
212
213   @Override
214   public void setUrlData(List<UrlLinkDisplay> links)
215   {
216     selectedUrls = new ArrayList<>();
217
218     Iterator<UrlLinkDisplay> it = links.iterator();
219     while (it.hasNext())
220     {
221       UrlLinkDisplay link = it.next();
222
223       // Handle links with MIRIAM ids only
224       if (isMiriamId(link.getId()))
225       {
226         // select/deselect links accordingly and set default url
227         if (urls.containsKey(link.getId()))
228         {
229           if (link.getIsSelected())
230           {
231             selectedUrls.add(link.getId());
232           }
233           if (link.getIsPrimary())
234           {
235             setPrimaryUrl(link.getId());
236           }
237         }
238       }
239     }
240   }
241
242   @Override
243   public String getPrimaryUrl(String seqid)
244   {
245     return super.getPrimaryUrl(seqid, urls);
246   }
247
248   @Override
249   public String getPrimaryUrlId()
250   {
251     return primaryUrl;
252   }
253
254   @Override
255   public String getPrimaryTarget(String seqid)
256   {
257     return null;
258   }
259
260   @Override
261   public String choosePrimaryUrl()
262   {
263     return null;
264   }
265
266   @Override
267   public boolean contains(String id)
268   {
269     return (urls.containsKey(id));
270   }
271 }