JAL-1064 patch for NPE when registerd database names do not resolve to one or more...
[jalview.git] / src / jalview / ws / seqfetcher / ASequenceFetcher.java
1 /*\r
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)\r
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle\r
4  * \r
5  * This file is part of Jalview.\r
6  * \r
7  * Jalview is free software: you can redistribute it and/or\r
8  * modify it under the terms of the GNU General Public License \r
9  * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r
10  * \r
11  * Jalview is distributed in the hope that it will be useful, but \r
12  * WITHOUT ANY WARRANTY; without even the implied warranty \r
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR \r
14  * PURPOSE.  See the GNU General Public License for more details.\r
15  * \r
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.\r
17  */\r
18 package jalview.ws.seqfetcher;\r
19 \r
20 import jalview.datamodel.AlignmentI;\r
21 import jalview.datamodel.DBRefEntry;\r
22 import jalview.datamodel.SequenceI;\r
23 import jalview.util.DBRefUtils;\r
24 \r
25 import java.util.ArrayList;\r
26 import java.util.Collection;\r
27 import java.util.Enumeration;\r
28 import java.util.HashSet;\r
29 import java.util.Hashtable;\r
30 import java.util.Iterator;\r
31 import java.util.List;\r
32 import java.util.Map;\r
33 import java.util.Stack;\r
34 import java.util.Vector;\r
35 \r
36 public class ASequenceFetcher\r
37 {\r
38 \r
39   /**\r
40    * set of databases we can retrieve entries from\r
41    */\r
42   protected Hashtable<String, Map<String, DbSourceProxy>> FETCHABLEDBS;\r
43 \r
44   public ASequenceFetcher()\r
45   {\r
46     super();\r
47   }\r
48 \r
49   /**\r
50    * get list of supported Databases\r
51    * \r
52    * @return database source string for each database - only the latest version\r
53    *         of a source db is bound to each source.\r
54    */\r
55   public String[] getSupportedDb()\r
56   {\r
57     if (FETCHABLEDBS == null)\r
58       return null;\r
59     String[] sf = new String[FETCHABLEDBS.size()];\r
60     Enumeration e = FETCHABLEDBS.keys();\r
61     int i = 0;\r
62     while (e.hasMoreElements())\r
63     {\r
64       sf[i++] = (String) e.nextElement();\r
65     }\r
66     ;\r
67     return sf;\r
68   }\r
69 \r
70   public boolean isFetchable(String source)\r
71   {\r
72     Enumeration e = FETCHABLEDBS.keys();\r
73     while (e.hasMoreElements())\r
74     {\r
75       String db = (String) e.nextElement();\r
76       if (source.compareToIgnoreCase(db) == 0)\r
77         return true;\r
78     }\r
79     jalview.bin.Cache.log.warn("isFetchable doesn't know about '" + source\r
80             + "'");\r
81     return false;\r
82   }\r
83 \r
84   public SequenceI[] getSequences(jalview.datamodel.DBRefEntry[] refs)\r
85   {\r
86     SequenceI[] ret = null;\r
87     Vector<SequenceI> rseqs = new Vector();\r
88     Hashtable<String, List<String>> queries = new Hashtable();\r
89     for (int r = 0; r < refs.length; r++)\r
90     {\r
91       if (!queries.containsKey(refs[r].getSource()))\r
92       {\r
93         queries.put(refs[r].getSource(), new ArrayList<String>());\r
94       }\r
95       List<String> qset = queries.get(refs[r].getSource());\r
96       if (!qset.contains(refs[r].getAccessionId()))\r
97       {\r
98         qset.add(refs[r].getAccessionId());\r
99       }\r
100     }\r
101     Enumeration<String> e = queries.keys();\r
102     while (e.hasMoreElements())\r
103     {\r
104       List<String> query = null;\r
105       String db = null;\r
106       db = e.nextElement();\r
107       query = queries.get(db);\r
108       if (!isFetchable(db))\r
109       {\r
110         reportStdError(db, query, new Exception(\r
111                 "Don't know how to fetch from this database :" + db));\r
112         continue;\r
113       }\r
114       Iterator<DbSourceProxy> fetchers = getSourceProxy(db).iterator();\r
115       Stack<String> queriesLeft = new Stack<String>();\r
116 //      List<String> queriesFailed = new ArrayList<String>();\r
117       queriesLeft.addAll(query);\r
118       while (fetchers.hasNext())\r
119       {\r
120         List<String> queriesMade = new ArrayList<String>();\r
121         HashSet queriesFound = new HashSet<String>();\r
122         try\r
123         {\r
124           DbSourceProxy fetcher = fetchers.next();\r
125           boolean doMultiple = fetcher.getAccessionSeparator() != null; // No\r
126           // separator\r
127           // - no\r
128           // Multiple\r
129           // Queries\r
130           while (!queriesLeft.isEmpty())\r
131           {\r
132             StringBuffer qsb = new StringBuffer();\r
133             do\r
134             {\r
135               if (qsb.length() > 0)\r
136               {\r
137                 qsb.append(fetcher.getAccessionSeparator());\r
138               }\r
139               String q = queriesLeft.pop();\r
140               queriesMade.add(q);\r
141               qsb.append(q);\r
142             } while (doMultiple && !queriesLeft.isEmpty());\r
143 \r
144             AlignmentI seqset = null;\r
145             try\r
146             {\r
147               // create a fetcher and go to it\r
148               seqset = fetcher.getSequenceRecords(qsb.toString()); // ,\r
149                       // queriesFailed);\r
150             } catch (Exception ex)\r
151             {\r
152               System.err.println("Failed to retrieve the following from "\r
153                       + db);\r
154               System.err.println(qsb);\r
155               ex.printStackTrace(System.err);\r
156             }\r
157             // TODO: Merge alignment together - perhaps\r
158             if (seqset != null)\r
159             {\r
160               SequenceI seqs[] = seqset.getSequencesArray();\r
161               if (seqs != null)\r
162               {\r
163                 for (int is = 0; is < seqs.length; is++)\r
164                 {\r
165                   rseqs.addElement(seqs[is]);\r
166                   DBRefEntry[] frefs = DBRefUtils.searchRefs(seqs[is]\r
167                           .getDBRef(), new DBRefEntry(db, null, null));\r
168                   if (frefs != null)\r
169                   {\r
170                     for (DBRefEntry dbr : frefs)\r
171                     {\r
172                       queriesFound.add(dbr.getAccessionId());\r
173                       queriesMade.remove(dbr.getAccessionId());\r
174                     }\r
175                   }\r
176                   seqs[is] = null;\r
177                 }\r
178               }\r
179               else\r
180               {\r
181                 if (fetcher.getRawRecords() != null)\r
182                 {\r
183                   System.out.println("# Retrieved from " + db + ":"\r
184                           + qsb.toString());\r
185                   StringBuffer rrb = fetcher.getRawRecords();\r
186                   /*\r
187                    * for (int rr = 0; rr<rrb.length; rr++) {\r
188                    */\r
189                   String hdr;\r
190                   // if (rr<qs.length)\r
191                   // {\r
192                   hdr = "# " + db + ":" + qsb.toString();\r
193                   /*\r
194                    * } else { hdr = "# part "+rr; }\r
195                    */\r
196                   System.out.println(hdr);\r
197                   if (rrb != null)\r
198                     System.out.println(rrb);\r
199                   System.out.println("# end of " + hdr);\r
200                 }\r
201 \r
202               }\r
203             }\r
204 \r
205           }\r
206         } catch (Exception ex)\r
207         {\r
208           reportStdError(db, queriesMade, ex);\r
209         }\r
210         if (queriesMade.size() > 0)\r
211         {\r
212           System.out.println("# Adding " + queriesMade.size()\r
213                   + " ids back to queries list for searching again (" + db\r
214                   + ".");\r
215           queriesLeft.addAll(queriesMade);\r
216         }\r
217       }\r
218     }\r
219     if (rseqs.size() > 0)\r
220     {\r
221       ret = new SequenceI[rseqs.size()];\r
222       Enumeration sqs = rseqs.elements();\r
223       int si = 0;\r
224       while (sqs.hasMoreElements())\r
225       {\r
226         SequenceI s = (SequenceI) sqs.nextElement();\r
227         ret[si++] = s;\r
228         s.updatePDBIds();\r
229       }\r
230     }\r
231     return ret;\r
232   }\r
233 \r
234   public void reportStdError(String db, List<String> queriesMade,\r
235           Exception ex)\r
236   {\r
237 \r
238     System.err.println("Failed to retrieve the following references from "\r
239             + db);\r
240     int n = 0;\r
241     for (String qv : queriesMade)\r
242     {\r
243       System.err.print(" " + qv + ";");\r
244       if (n++ > 10)\r
245       {\r
246         System.err.println();\r
247         n = 0;\r
248       }\r
249     }\r
250     System.err.println();\r
251     ex.printStackTrace();\r
252   }\r
253 \r
254   /**\r
255    * Retrieve an instance of the proxy for the given source\r
256    * \r
257    * @param db\r
258    *          database source string TODO: add version string/wildcard for\r
259    *          retrieval of specific DB source/version combinations.\r
260    * @return an instance of DbSourceProxy for that db.\r
261    */\r
262   public List<DbSourceProxy> getSourceProxy(String db)\r
263   {\r
264     List<DbSourceProxy> dbs;\r
265     Map<String,DbSourceProxy> dblist = FETCHABLEDBS.get(db);\r
266     if (dblist==null) {return new ArrayList<DbSourceProxy>();};\r
267     if (dblist.size()>1) {\r
268       DbSourceProxy[] l=dblist.values().toArray(new DbSourceProxy[0]);\r
269       int i=0;\r
270       String[] nm=new String[l.length];\r
271       for (DbSourceProxy s:l)\r
272       {\r
273         nm[i++]=s.getDbName().toLowerCase();\r
274       }\r
275       jalview.util.QuickSort.sort(nm,l);\r
276       dbs = new ArrayList<DbSourceProxy>();\r
277       for (i=l.length-1;i>=0; i--)\r
278       {\r
279         dbs.add(l[i]);\r
280       }\r
281     } else {\r
282       dbs = new ArrayList<DbSourceProxy>(dblist.values());\r
283     }\r
284     return dbs;\r
285   }\r
286 \r
287   /**\r
288    * constructs and instance of the proxy and registers it as a valid\r
289    * dbrefsource\r
290    * \r
291    * @param dbSourceProxy\r
292    *          reference for class implementing\r
293    *          jalview.ws.seqfetcher.DbSourceProxy\r
294    * @throws java.lang.IllegalArgumentException\r
295    *           if class does not implement jalview.ws.seqfetcher.DbSourceProxy\r
296    */\r
297   protected void addDBRefSourceImpl(Class dbSourceProxy)\r
298           throws java.lang.IllegalArgumentException\r
299   {\r
300     DbSourceProxy proxy = null;\r
301     try\r
302     {\r
303       Object proxyObj = dbSourceProxy.getConstructor(null)\r
304               .newInstance(null);\r
305       if (!DbSourceProxy.class.isInstance(proxyObj))\r
306       {\r
307         throw new IllegalArgumentException(\r
308                 dbSourceProxy.toString()\r
309                         + " does not implement the jalview.ws.seqfetcher.DbSourceProxy");\r
310       }\r
311       proxy = (DbSourceProxy) proxyObj;\r
312     } catch (IllegalArgumentException e)\r
313     {\r
314       throw e;\r
315     } catch (Exception e)\r
316     {\r
317       // Serious problems if this happens.\r
318       throw new Error("DBRefSource Implementation Exception", e);\r
319     }\r
320     addDbRefSourceImpl(proxy);\r
321   }\r
322 \r
323   /**\r
324    * add the properly initialised DbSourceProxy object 'proxy' to the list of\r
325    * sequence fetchers\r
326    * \r
327    * @param proxy\r
328    */\r
329   protected void addDbRefSourceImpl(DbSourceProxy proxy)\r
330   {\r
331     if (proxy != null)\r
332     {\r
333       if (FETCHABLEDBS == null)\r
334       {\r
335         FETCHABLEDBS = new Hashtable<String, Map<String,DbSourceProxy>>();\r
336       }\r
337       Map<String,DbSourceProxy> slist = FETCHABLEDBS.get(proxy.getDbSource());\r
338       if (slist == null)\r
339       {\r
340         FETCHABLEDBS.put(proxy.getDbSource(),\r
341                 slist = new Hashtable<String,DbSourceProxy>());\r
342       }\r
343       slist.put(proxy.getDbName(),proxy);\r
344     }\r
345   }\r
346 \r
347   /**\r
348    * test if the database handler for dbName contains the given dbProperty\r
349    * when a dbName resolves to a set of proxies - this method will return the result of the test for the first instance.\r
350    * TODO implement additional method to query all sources for a db to find one with a particular property\r
351    * @param dbName\r
352    * @param dbProperty\r
353    * @return true if proxy has the given property\r
354    */\r
355   public boolean hasDbSourceProperty(String dbName, String dbProperty)\r
356   {\r
357     // TODO: decide if invalidDbName exception is thrown here.\r
358 \r
359     List<DbSourceProxy> proxies = getSourceProxy(dbName);\r
360     if (proxies != null)\r
361     {\r
362       for (DbSourceProxy proxy : proxies)\r
363       {\r
364         if (proxy.getDbSourceProperties() != null)\r
365         {\r
366           return proxy.getDbSourceProperties().containsKey(dbProperty);\r
367         }\r
368       }\r
369     }\r
370     return false;\r
371   }\r
372 \r
373   /**\r
374    * select sources which are implemented by instances of the given class\r
375    * \r
376    * @param class that implements DbSourceProxy\r
377    * @return null or vector of source names for fetchers\r
378    */\r
379   public String[] getDbInstances(Class class1)\r
380   {\r
381     if (!jalview.ws.seqfetcher.DbSourceProxy.class.isAssignableFrom(class1))\r
382     {\r
383       throw new Error(\r
384               "Implmentation Error - getDbInstances must be given a class that implements jalview.ws.seqfetcher.DbSourceProxy (was given '"\r
385                       + class1 + "')");\r
386     }\r
387     if (FETCHABLEDBS == null)\r
388     {\r
389       return null;\r
390     }\r
391     String[] sources = null;\r
392     Vector src = new Vector();\r
393     Enumeration dbs = FETCHABLEDBS.keys();\r
394     while (dbs.hasMoreElements())\r
395     {\r
396       String dbn = (String) dbs.nextElement();\r
397       for (DbSourceProxy dbp : FETCHABLEDBS.get(dbn).values())\r
398       {\r
399         if (class1.isAssignableFrom(dbp.getClass()))\r
400         {\r
401           src.addElement(dbn);\r
402         }\r
403       }\r
404     }\r
405     if (src.size() > 0)\r
406     {\r
407       src.copyInto(sources = new String[src.size()]);\r
408     }\r
409     return sources;\r
410   }\r
411   public DbSourceProxy[] getDbSourceProxyInstances(\r
412           Class class1)\r
413   {\r
414     ArrayList<DbSourceProxy> prlist=new ArrayList<DbSourceProxy>();\r
415     for (String fetchable:getSupportedDb())\r
416     for (DbSourceProxy pr:getSourceProxy(fetchable))\r
417     {\r
418       if (class1.isInstance(pr)) {prlist.add(pr);}\r
419     }\r
420     if (prlist.size()==0)\r
421     {\r
422       return null;\r
423     }\r
424     return prlist.toArray(new DbSourceProxy[0]);\r
425   }\r
426 \r
427 }\r