JAL-2316 Changes following review.
[jalview.git] / src / jalview / urls / CustomUrlProvider.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 import static jalview.util.UrlConstants.SEQUENCE_ID;
28
29 import jalview.util.MessageManager;
30 import jalview.util.UrlConstants;
31 import jalview.util.UrlLink;
32
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.Map.Entry;
39 import java.util.StringTokenizer;
40 import java.util.Vector;
41
42 /**
43  * 
44  * Implements the UrlProviderI interface for a UrlProvider object which serves
45  * custom URLs defined by the user
46  * 
47  * @author $author$
48  * @version $Revision$
49  */
50 public class CustomUrlProvider extends UrlProviderImpl
51 {
52   // Default sequence URL link label for SRS
53   private static final String SRS_LABEL = "SRS";
54
55   // map of string ids to urlLinks (selected)
56   private HashMap<String, UrlLink> selectedUrls;
57
58   // map of string ids to urlLinks (not selected)
59   private HashMap<String, UrlLink> nonselectedUrls;
60
61   /**
62    * Construct UrlProvider for custom (user-entered) URLs
63    * 
64    * @param inMenuUrlList
65    *          list of URLs set to be displayed in menu, in form stored in Cache.
66    *          i.e. SEP delimited string
67    * @param storedUrlList
68    *          list of custom URLs entered by user but not currently displayed in
69    *          menu, in form stored in Cache
70    */
71   public CustomUrlProvider(String inMenuUrlList, String storedUrlList)
72   {
73     try
74     {
75       selectedUrls = parseUrlStrings(inMenuUrlList);
76       nonselectedUrls = parseUrlStrings(storedUrlList);
77     } catch (Exception ex)
78     {
79       System.out
80               .println(ex.getMessage() + "\nError parsing sequence links");
81     }
82   }
83
84   /**
85    * Construct UrlProvider for custom (user-entered) URLs
86    * 
87    * @param urlList
88    *          list of URLs to be displayed in menu, as (label,url) pairs
89    * @param storedUrlList
90    *          list of custom URLs entered by user but not currently displayed in
91    *          menu, as (label,url) pairs
92    */
93   public CustomUrlProvider(Map<String, String> inMenuUrlList,
94           Map<String, String> storedUrlList)
95   {
96     try
97     {
98       selectedUrls = parseUrlList(inMenuUrlList);
99       nonselectedUrls = parseUrlList(storedUrlList);
100     } catch (Exception ex)
101     {
102       System.out
103               .println(ex.getMessage() + "\nError parsing sequence links");
104     }
105   }
106
107   private HashMap<String, UrlLink> parseUrlStrings(String urlStrings)
108   {
109     // cachedUrlList is in form <label>|<url>|<label>|<url>...
110     // parse cachedUrlList into labels (used as id) and url links
111     HashMap<String, UrlLink> urls = new HashMap<String, UrlLink>();
112
113     StringTokenizer st = new StringTokenizer(urlStrings, SEP);
114     while (st.hasMoreElements())
115     {
116       String name = st.nextToken();
117
118       if (!isMiriamId(name))
119       {
120         // this one of our custom urls
121         String url = st.nextToken();
122         // check for '|' within a regex
123         int rxstart = url.indexOf(DELIM + DB_ACCESSION + DELIM);
124         if (rxstart == -1)
125         {
126           rxstart = url.indexOf(DELIM + SEQUENCE_ID + DELIM);
127         }
128         while (rxstart == -1 && url.indexOf("/=" + DELIM) == -1
129                 && st.hasMoreTokens())
130         {
131           url = url + SEP + st.nextToken();
132         }
133         urls.put(name, new UrlLink(name + SEP + url));
134       }
135     }
136     upgradeOldLinks(urls);
137     return urls;
138   }
139
140   private HashMap<String, UrlLink> parseUrlList(Map<String, String> urlList)
141   {
142     HashMap<String, UrlLink> urls = new HashMap<String, UrlLink>();
143     if (urlList == null)
144     {
145       return urls;
146     }
147
148     Iterator<Map.Entry<String, String>> it = urlList.entrySet().iterator();
149     while (it.hasNext())
150     {
151       Map.Entry<String, String> pair = it.next();
152       urls.put(pair.getKey(),
153               new UrlLink(pair.getKey() + SEP + pair.getValue()));
154     }
155     upgradeOldLinks(urls);
156     return urls;
157   }
158
159   /*
160    * Upgrade any legacy links which may have been left lying around
161    */
162   private void upgradeOldLinks(HashMap<String, UrlLink> urls)
163   {
164     // upgrade old SRS link
165     if (urls.containsKey(SRS_LABEL))
166     {
167       urls.remove(SRS_LABEL);
168       urls.put(UrlConstants.DEFAULT_LABEL, new UrlLink(UrlConstants.DEFAULT_STRING));
169     }
170   }
171
172   @Override
173   public Vector<String> getLinksForMenu()
174   {
175     Vector<String> links = new Vector<String>();
176     Iterator<Map.Entry<String, UrlLink>> it = selectedUrls.entrySet()
177             .iterator();
178     while (it.hasNext())
179     {
180       Map.Entry<String, UrlLink> pair = it.next();
181       links.add(pair.getValue().toString());
182     }
183     return links;
184   }
185
186   @Override
187   public List<UrlLinkDisplay> getLinksForTable()
188   {
189     ArrayList<UrlLinkDisplay> displayLinks = new ArrayList<UrlLinkDisplay>();
190     displayLinks = getLinksForTable(selectedUrls, true);
191     displayLinks.addAll(getLinksForTable(nonselectedUrls, false));
192     return displayLinks;
193   }
194
195   private ArrayList<UrlLinkDisplay> getLinksForTable(
196           HashMap<String, UrlLink> urlList, boolean selected)
197   {
198     return super.getLinksForTable(urlList, null, selected);
199   }
200
201   @Override
202   public boolean setPrimaryUrl(String id)
203   {
204     if (selectedUrls.containsKey(id))
205     {
206       primaryUrl = id;
207     }
208     else if (nonselectedUrls.containsKey(id))
209     {
210       primaryUrl = id;
211     }
212     else
213     {
214       primaryUrl = null;
215     }
216
217     return (primaryUrl != null);
218   }
219
220   @Override
221   public String writeUrlsAsString(boolean selected)
222   {
223     StringBuffer links = new StringBuffer();
224     HashMap<String, UrlLink> urls;
225     if (selected)
226     {
227       urls = selectedUrls;
228     }
229     else
230     {
231       urls = nonselectedUrls;
232     }
233     if (urls.size() > 0)
234     {
235       for (Entry<String, UrlLink> entry : urls.entrySet())
236       {
237         links.append(entry.getValue().toString());
238         links.append(SEP);
239       }
240
241       // remove last SEP
242       links.setLength(links.length() - 1);
243     }
244     else
245     {
246       urls.clear();
247     }
248     return links.toString();
249   }
250
251   @Override
252   public String getPrimaryUrl(String seqid)
253   {
254     String result = super.getPrimaryUrl(seqid, selectedUrls);
255     if (result == null)
256     {
257       result = super.getPrimaryUrl(seqid, nonselectedUrls);
258     }
259     return result;
260   }
261
262   @Override
263   public String getPrimaryUrlId()
264   {
265     return primaryUrl;
266   }
267
268   @Override
269   public String getPrimaryTarget(String seqid)
270   {
271     return selectedUrls.get(primaryUrl).getTarget();
272   }
273
274   @Override
275   public void setUrlData(List<UrlLinkDisplay> links)
276   {
277     HashMap<String, UrlLink> unselurls = new HashMap<String, UrlLink>();
278     HashMap<String, UrlLink> selurls = new HashMap<String, UrlLink>();
279
280     Iterator<UrlLinkDisplay> it = links.iterator();
281     while (it.hasNext())
282     {
283       UrlLinkDisplay link = it.next();
284
285       // MIRIAM ids will be handled by a different UrlProvider class
286       if (!isMiriamId(link.getId()))
287       {
288         // don't allow duplicate key names as entries will be overwritten
289         if (unselurls.containsKey(link.getId())
290                 || selurls.containsKey(link.getId()))
291         {
292           throw new IllegalArgumentException(MessageManager.formatMessage(
293                   "exception.url_cannot_have_duplicate_id", link.getId()));
294         }
295         if (link.getIsSelected())
296         {
297           selurls.put(link.getId(),
298                   new UrlLink(link.getName() + SEP + link.getUrl()));
299         }
300         else
301         {
302           unselurls.put(link.getId(), new UrlLink(link.getName() + SEP
303                   + link.getUrl()));
304         }
305         // sort out primary and selected ids
306         if (link.getIsPrimary())
307         {
308           setPrimaryUrl(link.getId());
309         }
310       }
311
312     }
313     nonselectedUrls = unselurls;
314     selectedUrls = selurls;
315   }
316
317   @Override
318   public String choosePrimaryUrl()
319   {
320     // unilaterally set the primary id to the EMBL_EBI link
321     if ((!nonselectedUrls.containsKey(UrlConstants.DEFAULT_LABEL))
322             && (!selectedUrls.containsKey(UrlConstants.DEFAULT_LABEL)))
323     {
324       selectedUrls.put(UrlConstants.DEFAULT_LABEL, new UrlLink(
325               UrlConstants.DEFAULT_STRING));
326     }
327     primaryUrl = UrlConstants.DEFAULT_LABEL;
328     return UrlConstants.DEFAULT_LABEL;
329   }
330
331   @Override
332   public boolean contains(String id)
333   {
334     return (selectedUrls.containsKey(id) || nonselectedUrls.containsKey(id));
335   }
336
337 }