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