JAL-3210 Improvements to eclipse detection. New src tree and SwingJS updated from...
[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.Map.Entry;
40 import java.util.Stack;
41 import java.util.Vector;
42
43 public class ASequenceFetcher
44 {
45
46   /*
47    * set of databases we can retrieve entries from
48    */
49   protected Hashtable<String, Map<String, DbSourceProxyRoot>> fetchableDbs;
50
51   /*
52    * comparator to sort by tier (0/1/2) and name
53    */
54   private Comparator<DbSourceProxy> proxyComparator;
55
56   /**
57    * Constructor
58    */
59   protected ASequenceFetcher()
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()
101             .toArray(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     return false;
116   }
117
118   /**
119    * Fetch sequences for the given cross-references
120    * 
121    * @param refs
122    * @param dna
123    *          if true, only fetch from nucleotide data sources, else peptide
124    * @return
125    */
126   public SequenceI[] getSequences(List<DBRefEntry> refs, boolean dna)
127   {
128     Vector<SequenceI> rseqs = new Vector<>();
129     Hashtable<String, List<String>> queries = new Hashtable<>();
130     for (DBRefEntry ref : refs)
131     {
132       String canonical = DBRefUtils.getCanonicalName(ref.getSource());
133       if (!queries.containsKey(canonical))
134       {
135         queries.put(canonical, new ArrayList<String>());
136       }
137       List<String> qset = queries.get(canonical);
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                   // BH 2015.01.25 check about version/accessid being null here
208                   List<DBRefEntry> frefs = DBRefUtils.searchRefs(
209                           seqs[is].getDBRefs(),
210                           new DBRefEntry(db, null, null), DBRefUtils.SEARCH_MODE_FULL);
211                   for (DBRefEntry dbr : frefs)
212                   {
213                     queriesFound.add(dbr.getAccessionId());
214                     queriesMade.remove(dbr.getAccessionId());
215                   }
216                   seqs[is] = null;
217                 }
218               }
219               else
220               {
221                 if (fetcher.getRawRecords() != null)
222                 {
223                   System.out.println(
224                           "# Retrieved from " + db + ":" + qsb.toString());
225                   StringBuffer rrb = fetcher.getRawRecords();
226                   /*
227                    * for (int rr = 0; rr<rrb.length; rr++) {
228                    */
229                   String hdr;
230                   // if (rr<qs.length)
231                   // {
232                   hdr = "# " + db + ":" + qsb.toString();
233                   /*
234                    * } else { hdr = "# part "+rr; }
235                    */
236                   System.out.println(hdr);
237                   if (rrb != null)
238                   {
239                     System.out.println(rrb);
240                   }
241                   System.out.println("# end of " + hdr);
242                 }
243
244               }
245             }
246
247           }
248         } catch (Exception ex)
249         {
250           reportStdError(db, queriesMade, ex);
251         }
252         if (queriesMade.size() > 0)
253         {
254           System.out.println("# Adding " + queriesMade.size()
255                   + " ids back to queries list for searching again (" + db
256                   + ")");
257           queriesLeft.addAll(queriesMade);
258         }
259       }
260     }
261
262     SequenceI[] result = null;
263     if (rseqs.size() > 0)
264     {
265       result = new SequenceI[rseqs.size()];
266       int si = 0;
267       for (SequenceI s : rseqs)
268       {
269         result[si++] = s;
270         s.updatePDBIds();
271       }
272     }
273     return result;
274   }
275
276   public void reportStdError(String db, List<String> queriesMade,
277           Exception ex)
278   {
279
280     System.err.println(
281             "Failed to retrieve the following references from " + db);
282     int n = 0;
283     for (String qv : queriesMade)
284     {
285       System.err.print(" " + qv + ";");
286       if (n++ > 10)
287       {
288         System.err.println();
289         n = 0;
290       }
291     }
292     System.err.println();
293     ex.printStackTrace();
294   }
295
296   /**
297    * Returns a list of proxies for the given source
298    * 
299    * @param db
300    *          database source string TODO: add version string/wildcard for
301    *          retrieval of specific DB source/version combinations.
302    * @return a list of DbSourceProxy for the db
303    */
304   public List<DbSourceProxy> getSourceProxy(String db)
305   {
306     db = DBRefUtils.getCanonicalName(db);
307     Map<String, DbSourceProxyRoot> dblist = fetchableDbs.get(db);
308     if (dblist == null)
309     {
310       return new ArrayList<>();
311     }
312
313     /*
314      * sort so that primary sources precede secondary
315      */
316     List<DbSourceProxy> dbs = new ArrayList<>();
317     for (Entry<String, DbSourceProxyRoot> entry : dblist.entrySet())
318     {
319       DbSourceProxyRoot proxy = entry.getValue();
320       if (proxy instanceof DbRoot)
321       {
322         proxy = setProxy((DbRoot) proxy, dblist);
323       }
324       dbs.add((DbSourceProxy) proxy);
325     }
326     Collections.sort(dbs, proxyComparator);
327     return dbs;
328   }
329
330   class DbRoot implements DbSourceProxyRoot
331   {
332
333     private String sourceName;
334
335     private String className;
336
337     DbRoot(String sourceName, String className)
338     {
339       this.sourceName = sourceName;
340       this.className = className;
341     }
342
343     @Override
344     public String getDbSource()
345     {
346       return sourceName;
347     }
348
349     /**
350      * lazy class creation
351      * 
352      * @return the actual proxy object
353      */
354     public DbSourceProxy getProxy()
355     {
356       try
357       {
358         System.err.println("ASeqFetch " + className);
359         return (DbSourceProxy) Class.forName(className).newInstance();
360       } catch (Exception e)
361       {
362         // Serious problems if this happens.
363         throw new Error(MessageManager.getString(
364                 "error.dbrefsource_implementation_exception"), e);
365       }
366     }
367
368   }
369
370   /**
371    * constructs an instance of the proxy and registers it as a valid dbrefsource
372    * 
373    * @param dbSourceProxyClass
374    *          reference for class implementing
375    *          jalview.ws.seqfetcher.DbSourceProxy
376    */
377   protected void addDBRefSourceImpl(
378           Class<? extends DbSourceProxy> dbSourceProxyClass)
379           throws IllegalArgumentException
380   {
381     DbSourceProxy proxy = null;
382     try
383     {
384       proxy = dbSourceProxyClass.getConstructor().newInstance();
385     } catch (IllegalArgumentException e)
386     {
387       throw e;
388     } catch (Exception e)
389     {
390       // Serious problems if this happens.
391       throw new Error(MessageManager
392               .getString("error.dbrefsource_implementation_exception"), e);
393     }
394     addDbRefSourceImpl(proxy);
395   }
396
397   public void addDBRefSourceImpl(String sourceName, String className)
398   {
399     addDbRefSourceImpl(new DbRoot(sourceName, className));
400   }
401
402   /**
403    * add the properly initialised DbSourceProxy object 'proxy' to the list of
404    * sequence fetchers
405    * 
406    * @param proxy
407    */
408   void addDbRefSourceImpl(DbSourceProxyRoot proxy)
409   {
410     if (proxy != null)
411     {
412       if (fetchableDbs == null)
413       {
414         fetchableDbs = new Hashtable<>();
415       }
416       String key = proxy.getDbSource();
417       Map<String, DbSourceProxyRoot> slist = fetchableDbs.get(key);
418       if (slist == null)
419       {
420         fetchableDbs.put(key, slist = new Hashtable<>());
421       }
422       if (proxy instanceof DbRoot)
423       {
424         slist.put("", proxy);
425       }
426       else
427       {
428         slist.put(((DbSourceProxy) proxy).getDbName(), proxy);
429       }
430     }
431   }
432
433   /**
434    * select sources which are implemented by instances of the given class
435    * 
436    * @param class1
437    *          that implements DbSourceProxy
438    * @return null or vector of source names for fetchers
439    */
440   public String[] getDbInstances(Class<?> class1)
441   {
442     if (!DbSourceProxy.class.isAssignableFrom(class1))
443     {
444       throw new Error(MessageManager.formatMessage(
445               "error.implementation_error_dbinstance_must_implement_interface",
446               new String[]
447               { class1.toString() }));
448     }
449     if (fetchableDbs == null)
450     {
451       return null;
452     }
453     Vector<String> src = new Vector<>();
454     for (String dbSource : fetchableDbs.keySet())
455     {
456       Map<String, DbSourceProxyRoot> dblist = fetchableDbs.get(dbSource);
457       for (Entry<String, DbSourceProxyRoot> entry : dblist.entrySet())
458       {
459         DbSourceProxyRoot proxy = entry.getValue();
460         if (proxy instanceof DbRoot)
461         {
462           proxy = setProxy((DbRoot) proxy, dblist);
463         }
464         Class<?> c = proxy.getClass();
465         if (class1 == c || class1.isAssignableFrom(c))
466         {
467           src.addElement(dbSource);
468         }
469       }
470     }
471     String[] sources = null;
472     if (src.size() > 0)
473     {
474       src.copyInto(sources = new String[src.size()]);
475     }
476     return sources;
477   }
478
479   private DbSourceProxyRoot setProxy(DbRoot root,
480           Map<String, DbSourceProxyRoot> dblist)
481   {
482     DbSourceProxy proxy = root.getProxy();
483     // Time to create the actual proxy
484     dblist.remove("");
485     dblist.put(proxy.getDbName(), proxy);
486     return proxy;
487   }
488
489   public DbSourceProxy[] getDbSourceProxyInstances(Class<?> class1)
490   {
491     if (fetchableDbs == null)
492     {
493       return null;
494     }
495     List<DbSourceProxy> prlist = new ArrayList<>();
496     for (String fetchable : fetchableDbs.keySet())
497     {
498       for (DbSourceProxy pr : getSourceProxy(fetchable))
499       {
500         if (class1.isInstance(pr))
501         {
502           prlist.add(pr);
503         }
504       }
505     }
506     if (prlist.size() == 0)
507     {
508       return null;
509     }
510     return prlist.toArray(new DbSourceProxy[0]);
511   }
512
513   /**
514    * Returns a preferred feature colouring scheme for the given source, or null
515    * if none is defined.
516    * 
517    * @param source
518    * @return
519    */
520   public FeatureSettingsModelI getFeatureColourScheme(String source)
521   {
522     /*
523      * return the first non-null colour scheme for any proxy for
524      * this database source
525      */
526     for (DbSourceProxy proxy : getSourceProxy(source))
527     {
528       FeatureSettingsModelI preferredColours = proxy
529               .getFeatureColourScheme();
530       if (preferredColours != null)
531       {
532         return preferredColours;
533       }
534     }
535     return null;
536   }
537 }