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