JAL-3253 preliminary static fixes for JavaScript part 2
[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     super();
62
63     /*
64      * comparator to sort proxies by tier and name
65      */
66     proxyComparator = new Comparator<DbSourceProxy>()
67     {
68       @Override
69       public int compare(DbSourceProxy o1, DbSourceProxy o2)
70       {
71         /*
72          * Tier 0 precedes 1 precedes 2
73          */
74         int compared = Integer.compare(o1.getTier(), o2.getTier());
75         if (compared == 0)
76         {
77           // defend against NullPointer - should never happen
78           String o1Name = o1.getDbName();
79           String o2Name = o2.getDbName();
80           if (o1Name != null && o2Name != null)
81           {
82             compared = o1Name.compareToIgnoreCase(o2Name);
83           }
84         }
85         return compared;
86       }
87     };
88   }
89
90   /**
91    * get array of supported Databases
92    * 
93    * @return database source string for each database - only the latest version
94    *         of a source db is bound to each source.
95    */
96   public String[] getSupportedDb()
97   {
98     if (fetchableDbs == null)
99     {
100       return null;
101     }
102     String[] sf = fetchableDbs.keySet()
103             .toArray(new String[fetchableDbs.size()]);
104     return sf;
105   }
106
107   public boolean isFetchable(String source)
108   {
109     for (String db : fetchableDbs.keySet())
110     {
111       if (source.equalsIgnoreCase(db))
112       {
113         return true;
114       }
115     }
116     Cache.log.warn("isFetchable doesn't know about '" + source + "'");
117     return false;
118   }
119
120   /**
121    * Fetch sequences for the given cross-references
122    * 
123    * @param refs
124    * @param dna
125    *          if true, only fetch from nucleotide data sources, else peptide
126    * @return
127    */
128   public SequenceI[] getSequences(List<DBRefEntry> refs, boolean dna)
129   {
130     Vector<SequenceI> rseqs = new Vector<>();
131     Hashtable<String, List<String>> queries = new Hashtable<>();
132     for (DBRefEntry ref : refs)
133     {
134       String canonical = DBRefUtils.getCanonicalName(ref.getSource());
135       if (!queries.containsKey(canonical))
136       {
137         queries.put(canonical, new ArrayList<String>());
138       }
139       List<String> qset = queries.get(canonical);
140       if (!qset.contains(ref.getAccessionId()))
141       {
142         qset.add(ref.getAccessionId());
143       }
144     }
145     Enumeration<String> e = queries.keys();
146     while (e.hasMoreElements())
147     {
148       List<String> query = null;
149       String db = null;
150       db = e.nextElement();
151       query = queries.get(db);
152       if (!isFetchable(db))
153       {
154         reportStdError(db, query, new Exception(
155                 "Don't know how to fetch from this database :" + db));
156         continue;
157       }
158
159       Stack<String> queriesLeft = new Stack<>();
160       queriesLeft.addAll(query);
161
162       List<DbSourceProxy> proxies = getSourceProxy(db);
163       for (DbSourceProxy fetcher : proxies)
164       {
165         List<String> queriesMade = new ArrayList<>();
166         HashSet<String> queriesFound = new HashSet<>();
167         try
168         {
169           if (fetcher.isDnaCoding() != dna)
170           {
171             continue; // wrong sort of data
172           }
173           boolean doMultiple = fetcher.getMaximumQueryCount() > 1;
174           while (!queriesLeft.isEmpty())
175           {
176             StringBuffer qsb = new StringBuffer();
177             do
178             {
179               if (qsb.length() > 0)
180               {
181                 qsb.append(fetcher.getAccessionSeparator());
182               }
183               String q = queriesLeft.pop();
184               queriesMade.add(q);
185               qsb.append(q);
186             } while (doMultiple && !queriesLeft.isEmpty());
187
188             AlignmentI seqset = null;
189             try
190             {
191               // create a fetcher and go to it
192               seqset = fetcher.getSequenceRecords(qsb.toString());
193             } catch (Exception ex)
194             {
195               System.err.println(
196                       "Failed to retrieve the following from " + 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                   // BH 2015.01.25 check about version/accessid being null here
210                   List<DBRefEntry> frefs = DBRefUtils.searchRefs(
211                           seqs[is].getDBRefs(),
212                           new DBRefEntry(db, null, null), DBRefUtils.SEARCH_MODE_FULL);
213                   for (DBRefEntry dbr : frefs)
214                   {
215                     queriesFound.add(dbr.getAccessionId());
216                     queriesMade.remove(dbr.getAccessionId());
217                   }
218                   seqs[is] = null;
219                 }
220               }
221               else
222               {
223                 if (fetcher.getRawRecords() != null)
224                 {
225                   System.out.println(
226                           "# Retrieved from " + db + ":" + 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(
283             "Failed to retrieve the following references from " + 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, DbSourceProxyRoot> dblist = fetchableDbs.get(db);
310     if (dblist == null)
311     {
312       return new ArrayList<>();
313     }
314
315     /*
316      * sort so that primary sources precede secondary
317      */
318     List<DbSourceProxy> dbs = new ArrayList<>();
319     for (Entry<String, DbSourceProxyRoot> entry : dblist.entrySet())
320     {
321       DbSourceProxyRoot proxy = entry.getValue();
322       if (proxy instanceof DbRoot)
323       {
324         proxy = setProxy((DbRoot) proxy, dblist);
325       }
326       dbs.add((DbSourceProxy) proxy);
327     }
328     Collections.sort(dbs, proxyComparator);
329     return dbs;
330   }
331
332   class DbRoot implements DbSourceProxyRoot
333   {
334
335     private String sourceName;
336
337     private String className;
338
339     DbRoot(String sourceName, String className)
340     {
341       this.sourceName = sourceName;
342       this.className = className;
343     }
344
345     @Override
346     public String getDbSource()
347     {
348       return sourceName;
349     }
350
351     /**
352      * lazy class creation
353      * 
354      * @return the actual proxy object
355      */
356     public DbSourceProxy getProxy()
357     {
358       try
359       {
360         System.err.println("ASeqFetch " + className);
361         return (DbSourceProxy) Class.forName(className).newInstance();
362       } catch (Exception e)
363       {
364         // Serious problems if this happens.
365         throw new Error(MessageManager.getString(
366                 "error.dbrefsource_implementation_exception"), e);
367       }
368     }
369
370   }
371
372   /**
373    * constructs an instance of the proxy and registers it as a valid dbrefsource
374    * 
375    * @param dbSourceProxyClass
376    *          reference for class implementing
377    *          jalview.ws.seqfetcher.DbSourceProxy
378    */
379   protected void addDBRefSourceImpl(
380           Class<? extends DbSourceProxy> dbSourceProxyClass)
381           throws IllegalArgumentException
382   {
383     DbSourceProxy proxy = null;
384     try
385     {
386       proxy = dbSourceProxyClass.getConstructor().newInstance();
387     } catch (IllegalArgumentException e)
388     {
389       throw e;
390     } catch (Exception e)
391     {
392       // Serious problems if this happens.
393       throw new Error(MessageManager
394               .getString("error.dbrefsource_implementation_exception"), e);
395     }
396     addDbRefSourceImpl(proxy);
397   }
398
399   public void addDBRefSourceImpl(String sourceName, String className)
400   {
401     addDbRefSourceImpl(new DbRoot(sourceName, className));
402   }
403
404   /**
405    * add the properly initialised DbSourceProxy object 'proxy' to the list of
406    * sequence fetchers
407    * 
408    * @param proxy
409    */
410   void addDbRefSourceImpl(DbSourceProxyRoot proxy)
411   {
412     if (proxy != null)
413     {
414       if (fetchableDbs == null)
415       {
416         fetchableDbs = new Hashtable<>();
417       }
418       String key = proxy.getDbSource();
419       Map<String, DbSourceProxyRoot> slist = fetchableDbs.get(key);
420       if (slist == null)
421       {
422         fetchableDbs.put(key, slist = new Hashtable<>());
423       }
424       if (proxy instanceof DbRoot)
425       {
426         slist.put("", proxy);
427       }
428       else
429       {
430         slist.put(((DbSourceProxy) proxy).getDbName(), proxy);
431       }
432     }
433   }
434
435   /**
436    * select sources which are implemented by instances of the given class
437    * 
438    * @param class1
439    *          that implements DbSourceProxy
440    * @return null or vector of source names for fetchers
441    */
442   public String[] getDbInstances(Class<?> class1)
443   {
444     if (!DbSourceProxy.class.isAssignableFrom(class1))
445     {
446       throw new Error(MessageManager.formatMessage(
447               "error.implementation_error_dbinstance_must_implement_interface",
448               new String[]
449               { class1.toString() }));
450     }
451     if (fetchableDbs == null)
452     {
453       return null;
454     }
455     Vector<String> src = new Vector<>();
456     for (String dbSource : fetchableDbs.keySet())
457     {
458       Map<String, DbSourceProxyRoot> dblist = fetchableDbs.get(dbSource);
459       for (Entry<String, DbSourceProxyRoot> entry : dblist.entrySet())
460       {
461         DbSourceProxyRoot proxy = entry.getValue();
462         if (proxy instanceof DbRoot)
463         {
464           proxy = setProxy((DbRoot) proxy, dblist);
465         }
466         Class<?> c = proxy.getClass();
467         if (class1 == c || class1.isAssignableFrom(c))
468         {
469           src.addElement(dbSource);
470         }
471       }
472     }
473     String[] sources = null;
474     if (src.size() > 0)
475     {
476       src.copyInto(sources = new String[src.size()]);
477     }
478     return sources;
479   }
480
481   private DbSourceProxyRoot setProxy(DbRoot root,
482           Map<String, DbSourceProxyRoot> dblist)
483   {
484     DbSourceProxy proxy = root.getProxy();
485     // Time to create the actual proxy
486     dblist.remove("");
487     dblist.put(proxy.getDbName(), proxy);
488     return proxy;
489   }
490
491   public DbSourceProxy[] getDbSourceProxyInstances(Class<?> class1)
492   {
493     if (fetchableDbs == null)
494     {
495       return null;
496     }
497     List<DbSourceProxy> prlist = new ArrayList<>();
498     for (String fetchable : fetchableDbs.keySet())
499     {
500       for (DbSourceProxy pr : getSourceProxy(fetchable))
501       {
502         if (class1.isInstance(pr))
503         {
504           prlist.add(pr);
505         }
506       }
507     }
508     if (prlist.size() == 0)
509     {
510       return null;
511     }
512     return prlist.toArray(new DbSourceProxy[0]);
513   }
514
515   /**
516    * Returns a preferred feature colouring scheme for the given source, or null
517    * if none is defined.
518    * 
519    * @param source
520    * @return
521    */
522   public FeatureSettingsModelI getFeatureColourScheme(String source)
523   {
524     /*
525      * return the first non-null colour scheme for any proxy for
526      * this database source
527      */
528     for (DbSourceProxy proxy : getSourceProxy(source))
529     {
530       FeatureSettingsModelI preferredColours = proxy
531               .getFeatureColourScheme();
532       if (preferredColours != null)
533       {
534         return preferredColours;
535       }
536     }
537     return null;
538   }
539 }