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