JAL-1705 temporary variable to aid inspection in debugger
[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       List<DbSourceProxy> proxies = getSourceProxy(db);
161       for (DbSourceProxy fetcher : proxies)
162       {
163         List<String> queriesMade = new ArrayList<String>();
164         HashSet<String> queriesFound = new HashSet<String>();
165         try
166         {
167           if (fetcher.isDnaCoding() != dna)
168           {
169             continue; // wrong sort of data
170           }
171           boolean doMultiple = fetcher.getAccessionSeparator() != null;
172           // No separator - no Multiple Queries
173           while (!queriesLeft.isEmpty())
174           {
175             StringBuffer qsb = new StringBuffer();
176             do
177             {
178               if (qsb.length() > 0)
179               {
180                 qsb.append(fetcher.getAccessionSeparator());
181               }
182               String q = queriesLeft.pop();
183               queriesMade.add(q);
184               qsb.append(q);
185             } while (doMultiple && !queriesLeft.isEmpty());
186
187             AlignmentI seqset = null;
188             try
189             {
190               // create a fetcher and go to it
191               seqset = fetcher.getSequenceRecords(qsb.toString()); // ,
192               // queriesFailed);
193             } catch (Exception ex)
194             {
195               System.err.println("Failed to retrieve the following from "
196                       + db);
197               System.err.println(qsb);
198               ex.printStackTrace(System.err);
199             }
200             // TODO: Merge alignment together - perhaps
201             if (seqset != null)
202             {
203               SequenceI seqs[] = seqset.getSequencesArray();
204               if (seqs != null)
205               {
206                 for (int is = 0; is < seqs.length; is++)
207                 {
208                   rseqs.addElement(seqs[is]);
209                   DBRefEntry[] frefs = DBRefUtils.searchRefs(seqs[is]
210                           .getDBRefs(), new DBRefEntry(db, null, null));
211                   if (frefs != null)
212                   {
213                     for (DBRefEntry dbr : frefs)
214                     {
215                       queriesFound.add(dbr.getAccessionId());
216                       queriesMade.remove(dbr.getAccessionId());
217                     }
218                   }
219                   seqs[is] = null;
220                 }
221               }
222               else
223               {
224                 if (fetcher.getRawRecords() != null)
225                 {
226                   System.out.println("# Retrieved from " + db + ":"
227                           + qsb.toString());
228                   StringBuffer rrb = fetcher.getRawRecords();
229                   /*
230                    * for (int rr = 0; rr<rrb.length; rr++) {
231                    */
232                   String hdr;
233                   // if (rr<qs.length)
234                   // {
235                   hdr = "# " + db + ":" + qsb.toString();
236                   /*
237                    * } else { hdr = "# part "+rr; }
238                    */
239                   System.out.println(hdr);
240                   if (rrb != null)
241                   {
242                     System.out.println(rrb);
243                   }
244                   System.out.println("# end of " + hdr);
245                 }
246
247               }
248             }
249
250           }
251         } catch (Exception ex)
252         {
253           reportStdError(db, queriesMade, ex);
254         }
255         if (queriesMade.size() > 0)
256         {
257           System.out.println("# Adding " + queriesMade.size()
258                   + " ids back to queries list for searching again (" + db
259                   + ".");
260           queriesLeft.addAll(queriesMade);
261         }
262       }
263     }
264
265     SequenceI[] result = null;
266     if (rseqs.size() > 0)
267     {
268       result = new SequenceI[rseqs.size()];
269       int si = 0;
270       for (SequenceI s : rseqs)
271       {
272         result[si++] = s;
273         s.updatePDBIds();
274       }
275     }
276     return result;
277   }
278
279   public void reportStdError(String db, List<String> queriesMade,
280           Exception ex)
281   {
282
283     System.err.println("Failed to retrieve the following references from "
284             + db);
285     int n = 0;
286     for (String qv : queriesMade)
287     {
288       System.err.print(" " + qv + ";");
289       if (n++ > 10)
290       {
291         System.err.println();
292         n = 0;
293       }
294     }
295     System.err.println();
296     ex.printStackTrace();
297   }
298
299   /**
300    * Returns a list of proxies for the given source
301    * 
302    * @param db
303    *          database source string TODO: add version string/wildcard for
304    *          retrieval of specific DB source/version combinations.
305    * @return a list of DbSourceProxy for the db
306    */
307   public List<DbSourceProxy> getSourceProxy(String db)
308   {
309     db = DBRefUtils.getCanonicalName(db);
310     Map<String, DbSourceProxy> dblist = fetchableDbs.get(db);
311     if (dblist == null)
312     {
313       return new ArrayList<DbSourceProxy>();
314     }
315
316     /*
317      * sort so that primary sources precede secondary
318      */
319     List<DbSourceProxy> dbs = new ArrayList<DbSourceProxy>(dblist.values());
320     Collections.sort(dbs, proxyComparator);
321     return dbs;
322   }
323
324   /**
325    * constructs an instance of the proxy and registers it as a valid dbrefsource
326    * 
327    * @param dbSourceProxy
328    *          reference for class implementing
329    *          jalview.ws.seqfetcher.DbSourceProxy
330    */
331   protected void addDBRefSourceImpl(
332           Class<? extends DbSourceProxy> dbSourceProxy)
333           throws IllegalArgumentException
334   {
335     DbSourceProxy proxy = null;
336     try
337     {
338       DbSourceProxy proxyObj = dbSourceProxy.getConstructor().newInstance();
339       proxy = proxyObj;
340     } catch (IllegalArgumentException e)
341     {
342       throw e;
343     } catch (Exception e)
344     {
345       // Serious problems if this happens.
346       throw new Error(
347               MessageManager
348                       .getString("error.dbrefsource_implementation_exception"),
349               e);
350     }
351     addDbRefSourceImpl(proxy);
352   }
353
354   /**
355    * add the properly initialised DbSourceProxy object 'proxy' to the list of
356    * sequence fetchers
357    * 
358    * @param proxy
359    */
360   protected void addDbRefSourceImpl(DbSourceProxy proxy)
361   {
362     if (proxy != null)
363     {
364       if (fetchableDbs == null)
365       {
366         fetchableDbs = new Hashtable<String, Map<String, DbSourceProxy>>();
367       }
368       Map<String, DbSourceProxy> slist = fetchableDbs.get(proxy
369               .getDbSource());
370       if (slist == null)
371       {
372         fetchableDbs.put(proxy.getDbSource(),
373                 slist = new Hashtable<String, DbSourceProxy>());
374       }
375       slist.put(proxy.getDbName(), proxy);
376     }
377   }
378
379   /**
380    * select sources which are implemented by instances of the given class
381    * 
382    * @param class that implements DbSourceProxy
383    * @return null or vector of source names for fetchers
384    */
385   public String[] getDbInstances(Class class1)
386   {
387     if (!DbSourceProxy.class.isAssignableFrom(class1))
388     {
389       throw new Error(
390               MessageManager
391                       .formatMessage(
392                               "error.implementation_error_dbinstance_must_implement_interface",
393                               new String[] { class1.toString() }));
394     }
395     if (fetchableDbs == null)
396     {
397       return null;
398     }
399     String[] sources = null;
400     Vector<String> src = new Vector<String>();
401     Enumeration<String> dbs = fetchableDbs.keys();
402     while (dbs.hasMoreElements())
403     {
404       String dbn = dbs.nextElement();
405       for (DbSourceProxy dbp : fetchableDbs.get(dbn).values())
406       {
407         if (class1.isAssignableFrom(dbp.getClass()))
408         {
409           src.addElement(dbn);
410         }
411       }
412     }
413     if (src.size() > 0)
414     {
415       src.copyInto(sources = new String[src.size()]);
416     }
417     return sources;
418   }
419
420   public DbSourceProxy[] getDbSourceProxyInstances(Class class1)
421   {
422     List<DbSourceProxy> prlist = new ArrayList<DbSourceProxy>();
423     for (String fetchable : getSupportedDb())
424     {
425       for (DbSourceProxy pr : getSourceProxy(fetchable))
426       {
427         if (class1.isInstance(pr))
428         {
429           prlist.add(pr);
430         }
431       }
432     }
433     if (prlist.size() == 0)
434     {
435       return null;
436     }
437     return prlist.toArray(new DbSourceProxy[0]);
438   }
439
440 }