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