JAL-1551 reorder imports
[jalview.git] / src / jalview / ws / SequenceFetcher.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;
22
23 import jalview.datamodel.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.SequenceI;
27 import jalview.ws.dbsources.das.api.jalviewSourceI;
28 import jalview.ws.seqfetcher.ASequenceFetcher;
29 import jalview.ws.seqfetcher.DbSourceProxy;
30
31 import java.util.ArrayList;
32 import java.util.Enumeration;
33 import java.util.List;
34 import java.util.Vector;
35
36 /**
37  * This is the the concrete implementation of the sequence retrieval interface
38  * and abstract class in jalview.ws.seqfetcher. This implements the run-time
39  * discovery of sequence database clients, and provides a hardwired main for
40  * testing all registered handlers.
41  * 
42  */
43 public class SequenceFetcher extends ASequenceFetcher
44 {
45   /**
46    * Thread safe construction of database proxies TODO: extend to a configurable
47    * database plugin mechanism where classes are instantiated by reflection and
48    * queried for their DbRefSource and version association.
49    * 
50    */
51   public SequenceFetcher()
52   {
53     this(true);
54   }
55
56   public SequenceFetcher(boolean addDas)
57   {
58     addDBRefSourceImpl(jalview.ws.dbsources.EmblSource.class);
59     addDBRefSourceImpl(jalview.ws.dbsources.EmblCdsSouce.class);
60     addDBRefSourceImpl(jalview.ws.dbsources.Uniprot.class);
61     addDBRefSourceImpl(jalview.ws.dbsources.UnprotName.class);
62     addDBRefSourceImpl(jalview.ws.dbsources.Pdb.class);
63     addDBRefSourceImpl(jalview.ws.dbsources.PfamFull.class);
64     addDBRefSourceImpl(jalview.ws.dbsources.PfamSeed.class);
65     // ensures Seed alignment is 'default' for PFAM
66     addDBRefSourceImpl(jalview.ws.dbsources.RfamFull.class);
67     addDBRefSourceImpl(jalview.ws.dbsources.RfamSeed.class);
68     if (addDas)
69     {
70       registerDasSequenceSources();
71     }
72   }
73
74   /**
75    * return an ordered list of database sources where non-das database classes
76    * appear before das database classes
77    */
78   public String[] getOrderedSupportedSources()
79   {
80     String[] srcs = this.getSupportedDb();
81     ArrayList<String> dassrc = new ArrayList<String>(), nondas = new ArrayList<String>();
82     for (int i = 0; i < srcs.length; i++)
83     {
84       boolean das = false, skip = false;
85       String nm;
86       for (DbSourceProxy dbs : getSourceProxy(srcs[i]))
87       {
88         // Skip the alignment databases for the moment - they're not useful for
89         // verifying a single sequence against its reference source
90         if (dbs.isA(DBRefSource.ALIGNMENTDB))
91         {
92           skip = true;
93         }
94         else
95         {
96           nm = dbs.getDbName();
97           if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
98           {
99             if (nm.startsWith("das:"))
100             {
101               nm = nm.substring(4);
102               das = true;
103             }
104             break;
105           }
106         }
107       }
108       if (skip)
109       {
110         continue;
111       }
112       if (das)
113       {
114         dassrc.add(srcs[i]);
115       }
116       else
117       {
118         nondas.add(srcs[i]);
119       }
120     }
121     String[] tosort = nondas.toArray(new String[0]), sorted = nondas
122             .toArray(new String[0]);
123     for (int j = 0, jSize = sorted.length; j < jSize; j++)
124     {
125       tosort[j] = tosort[j].toLowerCase();
126     }
127     jalview.util.QuickSort.sort(tosort, sorted);
128     // construct array with all sources listed
129
130     srcs = new String[sorted.length + dassrc.size()];
131     int i = 0;
132     for (int j = sorted.length - 1; j >= 0; j--, i++)
133     {
134       srcs[i] = sorted[j];
135       sorted[j] = null;
136     }
137
138     sorted = dassrc.toArray(new String[0]);
139     tosort = dassrc.toArray(new String[0]);
140     for (int j = 0, jSize = sorted.length; j < jSize; j++)
141     {
142       tosort[j] = tosort[j].toLowerCase();
143     }
144     jalview.util.QuickSort.sort(tosort, sorted);
145     for (int j = sorted.length - 1; j >= 0; j--, i++)
146     {
147       srcs[i] = sorted[j];
148     }
149     return srcs;
150   }
151
152   /**
153    * return plaintext databse list suitable for using in a GUI element
154    */
155   public String[] _getOrderedSupportedSources()
156   {
157     String[] srcs = this.getSupportedDb();
158     ArrayList dassrc = new ArrayList(), nondas = new ArrayList();
159     for (int i = 0; i < srcs.length; i++)
160     {
161       for (DbSourceProxy dbs : getSourceProxy(srcs[i]))
162       {
163         String nm = dbs.getDbName();
164         if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
165         {
166           if (nm.startsWith("das:"))
167           {
168             nm = nm.substring(4);
169           }
170           dassrc.add(new String[]
171           { srcs[i], nm.toUpperCase() });
172         }
173         else
174         {
175           nondas.add(new String[]
176           { srcs[i], nm.toUpperCase() });
177         }
178       }
179     }
180     Object[] sorted = nondas.toArray();
181     String[] tosort = new String[sorted.length];
182     nondas.clear();
183     for (int j = 0; j < sorted.length; j++)
184     {
185       tosort[j] = ((String[]) sorted[j])[1];
186     }
187     jalview.util.QuickSort.sort(tosort, sorted);
188     int i = 0;
189     // construct array with all sources listed
190     srcs = new String[sorted.length + dassrc.size()];
191     for (int j = sorted.length - 1; j >= 0; j--, i++)
192     {
193       srcs[i] = ((String[]) sorted[j])[0];
194       sorted[j] = null;
195     }
196
197     sorted = dassrc.toArray();
198     tosort = new String[sorted.length];
199     dassrc.clear();
200     for (int j = 0; j < sorted.length; j++)
201     {
202       tosort[j] = ((String[]) sorted[j])[1];
203     }
204     jalview.util.QuickSort.sort(tosort, sorted);
205     for (int j = sorted.length - 1; j >= 0; j--, i++)
206     {
207       srcs[i] = ((String[]) sorted[j])[0];
208       sorted[j] = null;
209     }
210     return srcs;
211   }
212
213   /**
214    * simple run method to test dbsources.
215    * 
216    * @param argv
217    */
218   public static void main(String[] argv)
219   {
220     AlignmentI ds = null;
221     Vector noProds = new Vector();
222     String usage = "SequenceFetcher.main [-nodas] [<DBNAME> [<ACCNO>]]\n"
223             + "With no arguments, all DbSources will be queried with their test Accession number.\n"
224             + "With one argument, the argument will be resolved to one or more db sources and each will be queried with their test accession only.\n"
225             + "If given two arguments, SequenceFetcher will try to find the DbFetcher corresponding to <DBNAME> and retrieve <ACCNO> from it.\n"
226             + "The -nodas option will exclude DAS sources from the database fetchers Jalview will try to use.";
227     boolean withDas = true;
228     if (argv != null && argv.length > 0
229             && argv[0].toLowerCase().startsWith("-nodas"))
230     {
231       withDas = false;
232       String targs[] = new String[argv.length - 1];
233       System.arraycopy(argv, 1, targs, 0, targs.length);
234       argv = targs;
235     }
236     if (argv != null && argv.length > 0)
237     {
238       List<DbSourceProxy> sps = new SequenceFetcher(withDas)
239               .getSourceProxy(argv[0]);
240
241       if (sps != null)
242       {
243         for (DbSourceProxy sp : sps)
244         {
245           AlignmentI al = null;
246           try
247           {
248             al = sp.getSequenceRecords(argv.length > 1 ? argv[1] : sp
249                     .getTestQuery());
250           } catch (Exception e)
251           {
252             e.printStackTrace();
253             System.err.println("Error when retrieving "
254                     + (argv.length > 1 ? argv[1] : sp.getTestQuery())
255                     + " from " + argv[0] + "\nUsage: " + usage);
256           }
257           SequenceI[] prod = al.getSequencesArray();
258           if (al != null)
259           {
260             for (int p = 0; p < prod.length; p++)
261             {
262               System.out.println("Prod " + p + ": "
263                       + prod[p].getDisplayId(true) + " : "
264                       + prod[p].getDescription());
265             }
266           }
267         }
268         return;
269       }
270       else
271       {
272         System.err.println("Can't resolve " + argv[0]
273                 + " as a database name. Allowed values are :\n"
274                 + new SequenceFetcher().getSupportedDb());
275       }
276       System.out.println(usage);
277       return;
278     }
279     ASequenceFetcher sfetcher = new SequenceFetcher(withDas);
280     String[] dbSources = sfetcher.getSupportedDb();
281     for (int dbsource = 0; dbsource < dbSources.length; dbsource++)
282     {
283       String db = dbSources[dbsource];
284       // skip me
285       if (db.equals(DBRefSource.PDB))
286       {
287         continue;
288       }
289       for (DbSourceProxy sp : sfetcher.getSourceProxy(db))
290       {
291         System.out.println("Source: " + sp.getDbName() + " (" + db
292                 + "): retrieving test:" + sp.getTestQuery());
293         AlignmentI al = null;
294         try
295         {
296           al = sp.getSequenceRecords(sp.getTestQuery());
297           if (al != null && al.getHeight() > 0
298                   && sp.getDbSourceProperties() != null)
299           {
300             boolean dna = sp.getDbSourceProperties().containsKey(
301                     DBRefSource.DNACODINGSEQDB)
302                     || sp.getDbSourceProperties().containsKey(
303                             DBRefSource.DNASEQDB)
304                     || sp.getDbSourceProperties().containsKey(
305                             DBRefSource.CODINGSEQDB);
306             // try and find products
307             String types[] = jalview.analysis.CrossRef
308                     .findSequenceXrefTypes(dna, al.getSequencesArray());
309             if (types != null)
310             {
311               System.out.println("Xref Types for: "
312                       + (dna ? "dna" : "prot"));
313               for (int t = 0; t < types.length; t++)
314               {
315                 System.out.println("Type: " + types[t]);
316                 SequenceI[] prod = jalview.analysis.CrossRef
317                         .findXrefSequences(al.getSequencesArray(), dna,
318                                 types[t]).getSequencesArray();
319                 System.out.println("Found "
320                         + ((prod == null) ? "no" : "" + prod.length)
321                         + " products");
322                 if (prod != null)
323                 {
324                   for (int p = 0; p < prod.length; p++)
325                   {
326                     System.out.println("Prod " + p + ": "
327                             + prod[p].getDisplayId(true));
328                   }
329                 }
330               }
331             }
332             else
333             {
334               noProds.addElement((dna ? new Object[]
335               { al, al } : new Object[]
336               { al }));
337             }
338
339           }
340         } catch (Exception ex)
341         {
342           System.out.println("ERROR:Failed to retrieve test query.");
343           ex.printStackTrace(System.out);
344         }
345
346         if (al == null)
347         {
348           System.out.println("ERROR:No alignment retrieved.");
349           StringBuffer raw = sp.getRawRecords();
350           if (raw != null)
351           {
352             System.out.println(raw.toString());
353           }
354           else
355           {
356             System.out.println("ERROR:No Raw results.");
357           }
358         }
359         else
360         {
361           System.out.println("Retrieved " + al.getHeight() + " sequences.");
362           for (int s = 0; s < al.getHeight(); s++)
363           {
364             SequenceI sq = al.getSequenceAt(s);
365             while (sq.getDatasetSequence() != null)
366             {
367               sq = sq.getDatasetSequence();
368
369             }
370             if (ds == null)
371             {
372               ds = new Alignment(new SequenceI[]
373               { sq });
374
375             }
376             else
377             {
378               ds.addSequence(sq);
379             }
380           }
381         }
382         System.out.flush();
383         System.err.flush();
384
385       }
386       if (noProds.size() > 0)
387       {
388         Enumeration ts = noProds.elements();
389         while (ts.hasMoreElements())
390
391         {
392           Object[] typeSq = (Object[]) ts.nextElement();
393           boolean dna = (typeSq.length > 1);
394           AlignmentI al = (AlignmentI) typeSq[0];
395           System.out.println("Trying getProducts for "
396                   + al.getSequenceAt(0).getDisplayId(true));
397           System.out.println("Search DS Xref for: "
398                   + (dna ? "dna" : "prot"));
399           // have a bash at finding the products amongst all the retrieved
400           // sequences.
401           SequenceI[] seqs = al.getSequencesArray();
402           Alignment prodal = jalview.analysis.CrossRef.findXrefSequences(
403                   seqs, dna, null, ds);
404           System.out.println("Found "
405                   + ((prodal == null) ? "no" : "" + prodal.getHeight())
406                   + " products");
407           if (prodal != null)
408           {
409             SequenceI[] prod = prodal.getSequencesArray(); // note
410             // should
411             // test
412             // rather
413             // than
414             // throw
415             // away
416             // codon
417             // mapping
418             // (if
419             // present)
420             for (int p = 0; p < prod.length; p++)
421             {
422               System.out.println("Prod " + p + ": "
423                       + prod[p].getDisplayId(true));
424             }
425           }
426         }
427
428       }
429
430     }
431   }
432
433   /**
434    * query the currently defined DAS source registry for sequence sources and
435    * add a DasSequenceSource instance for each source to the SequenceFetcher
436    * source list.
437    */
438   public void registerDasSequenceSources()
439   {
440     // TODO: define a context as a registry provider (either desktop,
441     // jalview.bin.cache, or something else).
442     for (jalviewSourceI source : jalview.bin.Cache.getDasSourceRegistry()
443             .getSources())
444     {
445       if (source.isSequenceSource())
446       {
447         List<DbSourceProxy> dassources = source.getSequenceSourceProxies();
448         for (DbSourceProxy seqsrc : dassources)
449         {
450           addDbRefSourceImpl(seqsrc);
451         }
452       }
453     }
454   }
455
456 }