JAL-2316 Moved url providers into own package
[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.EMBLEBI_LABEL;
25 //import static jalview.util.UrlConstants.EMBLEBI_STRING;
26 //import static jalview.util.UrlConstants.SRS_LABEL;
27
28
29 import static jalview.util.UrlConstants.DB_ACCESSION;
30 import static jalview.util.UrlConstants.DELIM;
31 import static jalview.util.UrlConstants.SEP;
32 import static jalview.util.UrlConstants.SEQUENCE_ID;
33
34 import jalview.util.MessageManager;
35 import jalview.util.UrlLink;
36
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.Map;
40 import java.util.StringTokenizer;
41 import java.util.Vector;
42
43 /**
44  * 
45  * Implements the UrlProviderI interface for a UrlProvider object which serves
46  * custom URLs defined by the user
47  * 
48  * @author $author$
49  * @version $Revision$
50  */
51 public class CustomUrlProvider extends UrlProviderImpl
52 {
53
54   // minimum length of substitution in url link string
55   private static final int MIN_SUBST_LENGTH = 4;
56
57   // Default sequence URL link label for SRS
58   private static final String SRS_LABEL = "SRS";
59
60   // map of string ids to urlLinks
61   private HashMap<String, UrlLink> urls;
62
63   /**
64    * Construct UrlProvider for custom (user-entered) URLs
65    * 
66    * @param cachedUrlList
67    *          list of URLs in form stored in Cache. i.e. SEP delimited string
68    */
69   public CustomUrlProvider(String cachedUrlList)
70   {
71     try
72     {
73       urls = new HashMap<String, UrlLink>();
74
75       // cachedUrlList is in form <label>|<url>|<label>|<url>...
76       // parse cachedUrlList into labels (used as id) and url links
77       StringTokenizer st = new StringTokenizer(cachedUrlList, SEP);
78       while (st.hasMoreElements())
79       {
80         String name = st.nextToken();
81         String url = st.nextToken();
82         // check for '|' within a regex
83         int rxstart = url.indexOf(DELIM + DB_ACCESSION + DELIM);
84         if (rxstart == -1)
85         {
86           rxstart = url.indexOf(DELIM + SEQUENCE_ID + DELIM);
87         }
88         while (rxstart == -1 && url.indexOf("/=" + DELIM) == -1)
89         {
90           url = url + SEP + st.nextToken();
91         }
92         urls.put(name, new UrlLink(name + SEP + url));
93       }
94     } catch (Exception ex)
95     {
96       System.out.println(ex + "\nError parsing sequence links");
97     }
98     upgradeOldLinks();
99
100   }
101
102   /**
103    * Construct UrlProvider for custom (user-entered) URLs
104    * 
105    * @param urlList
106    *          list of URLs as (label,url) pairs
107    */
108   public CustomUrlProvider(Map<String, String> urlList)
109   {
110     try
111     {
112       urls = new HashMap<String, UrlLink>();
113       Iterator<Map.Entry<String, String>> it = urlList.entrySet()
114               .iterator();
115       while (it.hasNext())
116       {
117         Map.Entry<String, String> pair = it.next();
118         urls.put(pair.getKey(),
119                 new UrlLink(pair.getKey() + SEP + pair.getValue()));
120       }
121     } catch (Exception ex)
122     {
123       System.out.println(ex + "\nError parsing sequence links");
124     }
125     upgradeOldLinks();
126   }
127
128   /*
129    * Upgrade any legacy links which may have been left lying around
130    */
131   private void upgradeOldLinks()
132   {
133     // upgrade old SRS link
134     if (urls.containsKey(SRS_LABEL))
135     {
136       urls.remove(SRS_LABEL);
137       urls.put(DEFAULT_LABEL, new UrlLink(DEFAULT_STRING));
138     }
139   }
140
141   @Override
142   public Vector<String> getLinksForDisplay()
143   {
144     Vector<String> links = new Vector<String>();
145     Iterator<Map.Entry<String, UrlLink>> it = urls.entrySet().iterator();
146     while (it.hasNext())
147     {
148       Map.Entry<String, UrlLink> pair = it.next();
149       links.add(pair.getValue().toString());
150     }
151     return links;
152   }
153
154   @Override
155   public boolean setDefaultUrl(String id)
156   {
157     if (urls.containsKey(id))
158     {
159       defaultUrl = id;
160     }
161     else
162     {
163       defaultUrl = null;
164     }
165     return urls.containsKey(id);
166   }
167
168   @Override
169   public String writeUrlsAsString()
170   {
171     StringBuffer links = new StringBuffer();
172     if (urls.size() > 0)
173     {
174       for (UrlLink link : urls.values())
175       {
176         links.append(link.toString());
177         links.append(SEP);
178       }
179
180       // remove last SEP
181       links.setLength(links.length() - 1);
182     }
183     else
184     {
185       urls.clear();
186     }
187     return links.toString();
188   }
189
190   @Override
191   public String getDefaultUrl(String seqid)
192   {
193     if (defaultUrl == null)
194     {
195       return null;
196     }
197
198     String url = null;
199     UrlLink urlLink = urls.get(defaultUrl);
200     String[] defaultUrls = urlLink.makeUrls(seqid, true);
201     if (defaultUrls == null || defaultUrls[0] == null
202             || defaultUrls[0].length() < MIN_SUBST_LENGTH)
203     {
204       url = null;
205     }
206     else
207     {
208       // just take first URL made from regex
209       url = defaultUrls[1];
210     }
211     return url;
212   }
213
214   @Override
215   public String getDefaultTarget(String seqid)
216   {
217     return urls.get(defaultUrl).getTarget();
218   }
219
220   @Override
221   public void setUrlLinks(Vector<String> names, Vector<String> urlstrings)
222   {
223     HashMap<String, UrlLink> newurls = new HashMap<String, UrlLink>();
224
225     // should check that lists are same length but this function is likely
226     // to change once the Preferences dialog is rebuilt
227
228     for (int i = 0; i < names.size(); ++i)
229     {
230       // don't allow MIRIAM ids as custom url names (as the links will overwrite
231       // each other)
232       // unlikely user would try to do this, but...
233       if (isMiriamId(names.elementAt(i)))
234       {
235         throw new IllegalArgumentException(MessageManager.formatMessage(
236                 "exception.url_cannot_have_miriam_id", names.elementAt(i)));
237       }
238       // don't allow duplicate key names as entries will be overwritten
239       if (newurls.containsKey(names.elementAt(i)))
240       {
241         throw new IllegalArgumentException(MessageManager.formatMessage(
242                 "exception.url_cannot_have_duplicate_id",
243                 names.elementAt(i)));
244       }
245       newurls.put(names.elementAt(i), new UrlLink(names.elementAt(i) + SEP
246               + urlstrings.elementAt(i)));
247     }
248
249     // don't update until we're sure this set is ok
250     urls = newurls;
251
252   }
253
254   @Override
255   public String chooseDefaultUrl()
256   {
257     // unilaterally set the default id to the EMBL_EBI link
258     
259     if (!urls.containsKey(DEFAULT_LABEL))
260     {
261       urls.put(DEFAULT_LABEL, new UrlLink(DEFAULT_STRING));
262     }
263     return DEFAULT_LABEL;
264   }
265
266 }