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