formatting
[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)\r
267     {\r
268       return new ArrayList<DbSourceProxy>();\r
269     }\r
270     ;\r
271     if (dblist.size() > 1)\r
272     {\r
273       DbSourceProxy[] l = dblist.values().toArray(new DbSourceProxy[0]);\r
274       int i = 0;\r
275       String[] nm = new String[l.length];\r
276       for (DbSourceProxy s : l)\r
277       {\r
278         nm[i++] = s.getDbName().toLowerCase();\r
279       }\r
280       jalview.util.QuickSort.sort(nm, l);\r
281       dbs = new ArrayList<DbSourceProxy>();\r
282       for (i = l.length - 1; i >= 0; i--)\r
283       {\r
284         dbs.add(l[i]);\r
285       }\r
286     }\r
287     else\r
288     {\r
289       dbs = new ArrayList<DbSourceProxy>(dblist.values());\r
290     }\r
291     return dbs;\r
292   }\r
293 \r
294   /**\r
295    * constructs and instance of the proxy and registers it as a valid\r
296    * dbrefsource\r
297    * \r
298    * @param dbSourceProxy\r
299    *          reference for class implementing\r
300    *          jalview.ws.seqfetcher.DbSourceProxy\r
301    * @throws java.lang.IllegalArgumentException\r
302    *           if class does not implement jalview.ws.seqfetcher.DbSourceProxy\r
303    */\r
304   protected void addDBRefSourceImpl(Class dbSourceProxy)\r
305           throws java.lang.IllegalArgumentException\r
306   {\r
307     DbSourceProxy proxy = null;\r
308     try\r
309     {\r
310       Object proxyObj = dbSourceProxy.getConstructor(null)\r
311               .newInstance(null);\r
312       if (!DbSourceProxy.class.isInstance(proxyObj))\r
313       {\r
314         throw new IllegalArgumentException(\r
315                 dbSourceProxy.toString()\r
316                         + " does not implement the jalview.ws.seqfetcher.DbSourceProxy");\r
317       }\r
318       proxy = (DbSourceProxy) proxyObj;\r
319     } catch (IllegalArgumentException e)\r
320     {\r
321       throw e;\r
322     } catch (Exception e)\r
323     {\r
324       // Serious problems if this happens.\r
325       throw new Error("DBRefSource Implementation Exception", e);\r
326     }\r
327     addDbRefSourceImpl(proxy);\r
328   }\r
329 \r
330   /**\r
331    * add the properly initialised DbSourceProxy object 'proxy' to the list of\r
332    * sequence fetchers\r
333    * \r
334    * @param proxy\r
335    */\r
336   protected void addDbRefSourceImpl(DbSourceProxy proxy)\r
337   {\r
338     if (proxy != null)\r
339     {\r
340       if (FETCHABLEDBS == null)\r
341       {\r
342         FETCHABLEDBS = new Hashtable<String, Map<String, DbSourceProxy>>();\r
343       }\r
344       Map<String, DbSourceProxy> slist = FETCHABLEDBS.get(proxy\r
345               .getDbSource());\r
346       if (slist == null)\r
347       {\r
348         FETCHABLEDBS.put(proxy.getDbSource(),\r
349                 slist = new Hashtable<String, DbSourceProxy>());\r
350       }\r
351       slist.put(proxy.getDbName(), proxy);\r
352     }\r
353   }\r
354 \r
355   /**\r
356    * test if the database handler for dbName contains the given dbProperty when\r
357    * a dbName resolves to a set of proxies - this method will return the result\r
358    * of the test for the first instance. TODO implement additional method to\r
359    * query all sources for a db to find one with a particular property\r
360    * \r
361    * @param dbName\r
362    * @param dbProperty\r
363    * @return true if proxy has the given property\r
364    */\r
365   public boolean hasDbSourceProperty(String dbName, String dbProperty)\r
366   {\r
367     // TODO: decide if invalidDbName exception is thrown here.\r
368 \r
369     List<DbSourceProxy> proxies = getSourceProxy(dbName);\r
370     if (proxies != null)\r
371     {\r
372       for (DbSourceProxy proxy : proxies)\r
373       {\r
374         if (proxy.getDbSourceProperties() != null)\r
375         {\r
376           return proxy.getDbSourceProperties().containsKey(dbProperty);\r
377         }\r
378       }\r
379     }\r
380     return false;\r
381   }\r
382 \r
383   /**\r
384    * select sources which are implemented by instances of the given class\r
385    * \r
386    * @param class that implements DbSourceProxy\r
387    * @return null or vector of source names for fetchers\r
388    */\r
389   public String[] getDbInstances(Class class1)\r
390   {\r
391     if (!jalview.ws.seqfetcher.DbSourceProxy.class.isAssignableFrom(class1))\r
392     {\r
393       throw new Error(\r
394               "Implmentation Error - getDbInstances must be given a class that implements jalview.ws.seqfetcher.DbSourceProxy (was given '"\r
395                       + class1 + "')");\r
396     }\r
397     if (FETCHABLEDBS == null)\r
398     {\r
399       return null;\r
400     }\r
401     String[] sources = null;\r
402     Vector src = new Vector();\r
403     Enumeration dbs = FETCHABLEDBS.keys();\r
404     while (dbs.hasMoreElements())\r
405     {\r
406       String dbn = (String) dbs.nextElement();\r
407       for (DbSourceProxy dbp : FETCHABLEDBS.get(dbn).values())\r
408       {\r
409         if (class1.isAssignableFrom(dbp.getClass()))\r
410         {\r
411           src.addElement(dbn);\r
412         }\r
413       }\r
414     }\r
415     if (src.size() > 0)\r
416     {\r
417       src.copyInto(sources = new String[src.size()]);\r
418     }\r
419     return sources;\r
420   }\r
421 \r
422   public DbSourceProxy[] getDbSourceProxyInstances(Class class1)\r
423   {\r
424     ArrayList<DbSourceProxy> prlist = new ArrayList<DbSourceProxy>();\r
425     for (String fetchable : getSupportedDb())\r
426       for (DbSourceProxy pr : getSourceProxy(fetchable))\r
427       {\r
428         if (class1.isInstance(pr))\r
429         {\r
430           prlist.add(pr);\r
431         }\r
432       }\r
433     if (prlist.size() == 0)\r
434     {\r
435       return null;\r
436     }\r
437     return prlist.toArray(new DbSourceProxy[0]);\r
438   }\r
439 \r
440 }\r