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