JAL-1807 explicit imports (jalview.ws.*)
[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 import jalview.util.QuickSort;
30
31 import java.util.ArrayList;
32 import java.util.Enumeration;
33 import java.util.HashSet;
34 import java.util.Hashtable;
35 import java.util.Iterator;
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   public ASequenceFetcher()
50   {
51     super();
52   }
53
54   /**
55    * get list of supported Databases
56    * 
57    * @return database source string for each database - only the latest version
58    *         of a source db is bound to each source.
59    */
60   public String[] getSupportedDb()
61   {
62     if (FETCHABLEDBS == null)
63     {
64       return null;
65     }
66     String[] sf = new String[FETCHABLEDBS.size()];
67     Enumeration e = FETCHABLEDBS.keys();
68     int i = 0;
69     while (e.hasMoreElements())
70     {
71       sf[i++] = (String) e.nextElement();
72     }
73     ;
74     return sf;
75   }
76
77   public boolean isFetchable(String source)
78   {
79     Enumeration e = FETCHABLEDBS.keys();
80     while (e.hasMoreElements())
81     {
82       String db = (String) e.nextElement();
83       if (source.compareToIgnoreCase(db) == 0)
84       {
85         return true;
86       }
87     }
88     Cache.log.warn("isFetchable doesn't know about '" + source
89             + "'");
90     return false;
91   }
92
93   public SequenceI[] getSequences(DBRefEntry[] refs)
94   {
95     SequenceI[] ret = null;
96     Vector<SequenceI> rseqs = new Vector();
97     Hashtable<String, List<String>> queries = new Hashtable();
98     for (int r = 0; r < refs.length; r++)
99     {
100       if (!queries.containsKey(refs[r].getSource()))
101       {
102         queries.put(refs[r].getSource(), new ArrayList<String>());
103       }
104       List<String> qset = queries.get(refs[r].getSource());
105       if (!qset.contains(refs[r].getAccessionId()))
106       {
107         qset.add(refs[r].getAccessionId());
108       }
109     }
110     Enumeration<String> e = queries.keys();
111     while (e.hasMoreElements())
112     {
113       List<String> query = null;
114       String db = null;
115       db = e.nextElement();
116       query = queries.get(db);
117       if (!isFetchable(db))
118       {
119         reportStdError(db, query, new Exception(
120                 "Don't know how to fetch from this database :" + db));
121         continue;
122       }
123       Iterator<DbSourceProxy> fetchers = getSourceProxy(db).iterator();
124       Stack<String> queriesLeft = new Stack<String>();
125       // List<String> queriesFailed = new ArrayList<String>();
126       queriesLeft.addAll(query);
127       while (fetchers.hasNext())
128       {
129         List<String> queriesMade = new ArrayList<String>();
130         HashSet queriesFound = new HashSet<String>();
131         try
132         {
133           DbSourceProxy fetcher = fetchers.next();
134           boolean doMultiple = fetcher.getAccessionSeparator() != null; // No
135           // separator
136           // - no
137           // Multiple
138           // Queries
139           while (!queriesLeft.isEmpty())
140           {
141             StringBuffer qsb = new StringBuffer();
142             do
143             {
144               if (qsb.length() > 0)
145               {
146                 qsb.append(fetcher.getAccessionSeparator());
147               }
148               String q = queriesLeft.pop();
149               queriesMade.add(q);
150               qsb.append(q);
151             } while (doMultiple && !queriesLeft.isEmpty());
152
153             AlignmentI seqset = null;
154             try
155             {
156               // create a fetcher and go to it
157               seqset = fetcher.getSequenceRecords(qsb.toString()); // ,
158               // queriesFailed);
159             } catch (Exception ex)
160             {
161               System.err.println("Failed to retrieve the following from "
162                       + db);
163               System.err.println(qsb);
164               ex.printStackTrace(System.err);
165             }
166             // TODO: Merge alignment together - perhaps
167             if (seqset != null)
168             {
169               SequenceI seqs[] = seqset.getSequencesArray();
170               if (seqs != null)
171               {
172                 for (int is = 0; is < seqs.length; is++)
173                 {
174                   rseqs.addElement(seqs[is]);
175                   DBRefEntry[] frefs = DBRefUtils.searchRefs(seqs[is]
176                           .getDBRef(), new DBRefEntry(db, null, null));
177                   if (frefs != null)
178                   {
179                     for (DBRefEntry dbr : frefs)
180                     {
181                       queriesFound.add(dbr.getAccessionId());
182                       queriesMade.remove(dbr.getAccessionId());
183                     }
184                   }
185                   seqs[is] = null;
186                 }
187               }
188               else
189               {
190                 if (fetcher.getRawRecords() != null)
191                 {
192                   System.out.println("# Retrieved from " + db + ":"
193                           + qsb.toString());
194                   StringBuffer rrb = fetcher.getRawRecords();
195                   /*
196                    * for (int rr = 0; rr<rrb.length; rr++) {
197                    */
198                   String hdr;
199                   // if (rr<qs.length)
200                   // {
201                   hdr = "# " + db + ":" + qsb.toString();
202                   /*
203                    * } else { hdr = "# part "+rr; }
204                    */
205                   System.out.println(hdr);
206                   if (rrb != null)
207                   {
208                     System.out.println(rrb);
209                   }
210                   System.out.println("# end of " + hdr);
211                 }
212
213               }
214             }
215
216           }
217         } catch (Exception ex)
218         {
219           reportStdError(db, queriesMade, ex);
220         }
221         if (queriesMade.size() > 0)
222         {
223           System.out.println("# Adding " + queriesMade.size()
224                   + " ids back to queries list for searching again (" + db
225                   + ".");
226           queriesLeft.addAll(queriesMade);
227         }
228       }
229     }
230     if (rseqs.size() > 0)
231     {
232       ret = new SequenceI[rseqs.size()];
233       Enumeration sqs = rseqs.elements();
234       int si = 0;
235       while (sqs.hasMoreElements())
236       {
237         SequenceI s = (SequenceI) sqs.nextElement();
238         ret[si++] = s;
239         s.updatePDBIds();
240       }
241     }
242     return ret;
243   }
244
245   public void reportStdError(String db, List<String> queriesMade,
246           Exception ex)
247   {
248
249     System.err.println("Failed to retrieve the following references from "
250             + db);
251     int n = 0;
252     for (String qv : queriesMade)
253     {
254       System.err.print(" " + qv + ";");
255       if (n++ > 10)
256       {
257         System.err.println();
258         n = 0;
259       }
260     }
261     System.err.println();
262     ex.printStackTrace();
263   }
264
265   /**
266    * Retrieve an instance of the proxy for the given source
267    * 
268    * @param db
269    *          database source string TODO: add version string/wildcard for
270    *          retrieval of specific DB source/version combinations.
271    * @return an instance of DbSourceProxy for that db.
272    */
273   public List<DbSourceProxy> getSourceProxy(String db)
274   {
275     List<DbSourceProxy> dbs;
276     Map<String, DbSourceProxy> dblist = FETCHABLEDBS.get(db);
277     if (dblist == null)
278     {
279       return new ArrayList<DbSourceProxy>();
280     }
281     ;
282     if (dblist.size() > 1)
283     {
284       DbSourceProxy[] l = dblist.values().toArray(new DbSourceProxy[0]);
285       int i = 0;
286       String[] nm = new String[l.length];
287       // make sure standard dbs appear first, followed by reference das sources,
288       // followed by anything else.
289       for (DbSourceProxy s : l)
290       {
291         nm[i++] = "" + s.getTier() + s.getDbName().toLowerCase();
292       }
293       QuickSort.sort(nm, l);
294       dbs = new ArrayList<DbSourceProxy>();
295       for (i = l.length - 1; i >= 0; i--)
296       {
297         dbs.add(l[i]);
298       }
299     }
300     else
301     {
302       dbs = new ArrayList<DbSourceProxy>(dblist.values());
303     }
304     return dbs;
305   }
306
307   /**
308    * constructs and instance of the proxy and registers it as a valid
309    * dbrefsource
310    * 
311    * @param dbSourceProxy
312    *          reference for class implementing
313    *          jalview.ws.seqfetcher.DbSourceProxy
314    */
315   protected void addDBRefSourceImpl(
316           Class<? extends DbSourceProxy> dbSourceProxy)
317           throws java.lang.IllegalArgumentException
318   {
319     DbSourceProxy proxy = null;
320     try
321     {
322       DbSourceProxy proxyObj = dbSourceProxy.getConstructor().newInstance();
323       proxy = 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 (!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     {
430       for (DbSourceProxy pr : getSourceProxy(fetchable))
431       {
432         if (class1.isInstance(pr))
433         {
434           prlist.add(pr);
435         }
436       }
437     }
438     if (prlist.size() == 0)
439     {
440       return null;
441     }
442     return prlist.toArray(new DbSourceProxy[0]);
443   }
444
445 }