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