2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.ws.seqfetcher;
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;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.Comparator;
33 import java.util.Enumeration;
34 import java.util.HashSet;
35 import java.util.Hashtable;
36 import java.util.List;
38 import java.util.Stack;
39 import java.util.Vector;
41 public class ASequenceFetcher
45 * set of databases we can retrieve entries from
47 protected Hashtable<String, Map<String, DbSourceProxy>> fetchableDbs;
50 * comparator to sort by tier (0/1/2) and name
52 private Comparator<DbSourceProxy> proxyComparator;
57 public ASequenceFetcher()
62 * comparator to sort proxies by tier and name
64 proxyComparator = new Comparator<DbSourceProxy>()
67 public int compare(DbSourceProxy o1, DbSourceProxy o2)
70 * Tier 0 precedes 1 precedes 2
72 int compared = Integer.compare(o1.getTier(), o2.getTier());
75 // defend against NullPointer - should never happen
76 String o1Name = o1.getDbName();
77 String o2Name = o2.getDbName();
78 if (o1Name != null && o2Name != null)
80 compared = o1Name.compareToIgnoreCase(o2Name);
89 * get array of supported Databases
91 * @return database source string for each database - only the latest version
92 * of a source db is bound to each source.
94 public String[] getSupportedDb()
96 if (fetchableDbs == null)
100 String[] sf = fetchableDbs.keySet().toArray(
101 new String[fetchableDbs.size()]);
105 public boolean isFetchable(String source)
107 for (String db : fetchableDbs.keySet())
109 if (source.equalsIgnoreCase(db))
114 Cache.log.warn("isFetchable doesn't know about '" + source
120 * Fetch sequences for the given cross-references
124 * if true, only fetch from nucleotide data sources, else peptide
127 public SequenceI[] getSequences(DBRefEntry[] refs, boolean dna)
129 Vector<SequenceI> rseqs = new Vector<SequenceI>();
130 Hashtable<String, List<String>> queries = new Hashtable<String, List<String>>();
131 for (int r = 0; r < refs.length; r++)
133 if (!queries.containsKey(refs[r].getSource()))
135 queries.put(refs[r].getSource(), new ArrayList<String>());
137 List<String> qset = queries.get(refs[r].getSource());
138 if (!qset.contains(refs[r].getAccessionId()))
140 qset.add(refs[r].getAccessionId());
143 Enumeration<String> e = queries.keys();
144 while (e.hasMoreElements())
146 List<String> query = null;
148 db = e.nextElement();
149 query = queries.get(db);
150 if (!isFetchable(db))
152 reportStdError(db, query, new Exception(
153 "Don't know how to fetch from this database :" + db));
157 Stack<String> queriesLeft = new Stack<String>();
158 queriesLeft.addAll(query);
160 List<DbSourceProxy> proxies = getSourceProxy(db);
161 for (DbSourceProxy fetcher : proxies)
163 List<String> queriesMade = new ArrayList<String>();
164 HashSet<String> queriesFound = new HashSet<String>();
167 if (fetcher.isDnaCoding() != dna)
169 continue; // wrong sort of data
171 boolean doMultiple = fetcher.getAccessionSeparator() != null;
172 // No separator - no Multiple Queries
173 while (!queriesLeft.isEmpty())
175 StringBuffer qsb = new StringBuffer();
178 if (qsb.length() > 0)
180 qsb.append(fetcher.getAccessionSeparator());
182 String q = queriesLeft.pop();
185 } while (doMultiple && !queriesLeft.isEmpty());
187 AlignmentI seqset = null;
190 // create a fetcher and go to it
191 seqset = fetcher.getSequenceRecords(qsb.toString()); // ,
193 } catch (Exception ex)
195 System.err.println("Failed to retrieve the following from "
197 System.err.println(qsb);
198 ex.printStackTrace(System.err);
200 // TODO: Merge alignment together - perhaps
203 SequenceI seqs[] = seqset.getSequencesArray();
206 for (int is = 0; is < seqs.length; is++)
208 rseqs.addElement(seqs[is]);
209 DBRefEntry[] frefs = DBRefUtils.searchRefs(seqs[is]
210 .getDBRefs(), new DBRefEntry(db, null, null));
213 for (DBRefEntry dbr : frefs)
215 queriesFound.add(dbr.getAccessionId());
216 queriesMade.remove(dbr.getAccessionId());
224 if (fetcher.getRawRecords() != null)
226 System.out.println("# Retrieved from " + db + ":"
228 StringBuffer rrb = fetcher.getRawRecords();
230 * for (int rr = 0; rr<rrb.length; rr++) {
235 hdr = "# " + db + ":" + qsb.toString();
237 * } else { hdr = "# part "+rr; }
239 System.out.println(hdr);
242 System.out.println(rrb);
244 System.out.println("# end of " + hdr);
251 } catch (Exception ex)
253 reportStdError(db, queriesMade, ex);
255 if (queriesMade.size() > 0)
257 System.out.println("# Adding " + queriesMade.size()
258 + " ids back to queries list for searching again (" + db
260 queriesLeft.addAll(queriesMade);
265 SequenceI[] result = null;
266 if (rseqs.size() > 0)
268 result = new SequenceI[rseqs.size()];
270 for (SequenceI s : rseqs)
279 public void reportStdError(String db, List<String> queriesMade,
283 System.err.println("Failed to retrieve the following references from "
286 for (String qv : queriesMade)
288 System.err.print(" " + qv + ";");
291 System.err.println();
295 System.err.println();
296 ex.printStackTrace();
300 * Returns a list of proxies for the given source
303 * database source string TODO: add version string/wildcard for
304 * retrieval of specific DB source/version combinations.
305 * @return a list of DbSourceProxy for the db
307 public List<DbSourceProxy> getSourceProxy(String db)
309 db = DBRefUtils.getCanonicalName(db);
310 Map<String, DbSourceProxy> dblist = fetchableDbs.get(db);
313 return new ArrayList<DbSourceProxy>();
317 * sort so that primary sources precede secondary
319 List<DbSourceProxy> dbs = new ArrayList<DbSourceProxy>(dblist.values());
320 Collections.sort(dbs, proxyComparator);
325 * constructs an instance of the proxy and registers it as a valid dbrefsource
327 * @param dbSourceProxy
328 * reference for class implementing
329 * jalview.ws.seqfetcher.DbSourceProxy
331 protected void addDBRefSourceImpl(
332 Class<? extends DbSourceProxy> dbSourceProxy)
333 throws IllegalArgumentException
335 DbSourceProxy proxy = null;
338 DbSourceProxy proxyObj = dbSourceProxy.getConstructor().newInstance();
340 } catch (IllegalArgumentException e)
343 } catch (Exception e)
345 // Serious problems if this happens.
348 .getString("error.dbrefsource_implementation_exception"),
351 addDbRefSourceImpl(proxy);
355 * add the properly initialised DbSourceProxy object 'proxy' to the list of
360 protected void addDbRefSourceImpl(DbSourceProxy proxy)
364 if (fetchableDbs == null)
366 fetchableDbs = new Hashtable<String, Map<String, DbSourceProxy>>();
368 Map<String, DbSourceProxy> slist = fetchableDbs.get(proxy
372 fetchableDbs.put(proxy.getDbSource(),
373 slist = new Hashtable<String, DbSourceProxy>());
375 slist.put(proxy.getDbName(), proxy);
380 * select sources which are implemented by instances of the given class
382 * @param class that implements DbSourceProxy
383 * @return null or vector of source names for fetchers
385 public String[] getDbInstances(Class class1)
387 if (!DbSourceProxy.class.isAssignableFrom(class1))
392 "error.implementation_error_dbinstance_must_implement_interface",
393 new String[] { class1.toString() }));
395 if (fetchableDbs == null)
399 String[] sources = null;
400 Vector<String> src = new Vector<String>();
401 Enumeration<String> dbs = fetchableDbs.keys();
402 while (dbs.hasMoreElements())
404 String dbn = dbs.nextElement();
405 for (DbSourceProxy dbp : fetchableDbs.get(dbn).values())
407 if (class1.isAssignableFrom(dbp.getClass()))
415 src.copyInto(sources = new String[src.size()]);
420 public DbSourceProxy[] getDbSourceProxyInstances(Class class1)
422 List<DbSourceProxy> prlist = new ArrayList<DbSourceProxy>();
423 for (String fetchable : getSupportedDb())
425 for (DbSourceProxy pr : getSourceProxy(fetchable))
427 if (class1.isInstance(pr))
433 if (prlist.size() == 0)
437 return prlist.toArray(new DbSourceProxy[0]);