JAL-1064 - refactor to iterate over many sources associated with a database authority
[jalview.git] / src / jalview / ws / SequenceFetcher.java
1 /*\r
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)\r
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle\r
4  * \r
5  * This file is part of Jalview.\r
6  * \r
7  * Jalview is free software: you can redistribute it and/or\r
8  * modify it under the terms of the GNU General Public License \r
9  * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r
10  * \r
11  * Jalview is distributed in the hope that it will be useful, but \r
12  * WITHOUT ANY WARRANTY; without even the implied warranty \r
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR \r
14  * PURPOSE.  See the GNU General Public License for more details.\r
15  * \r
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.\r
17  */\r
18 package jalview.ws;\r
19 \r
20 import jalview.datamodel.Alignment;\r
21 import jalview.datamodel.AlignmentI;\r
22 import jalview.datamodel.DBRefSource;\r
23 import jalview.datamodel.SequenceI;\r
24 import jalview.ws.dbsources.das.api.jalviewSourceI;\r
25 import jalview.ws.seqfetcher.ASequenceFetcher;\r
26 import jalview.ws.seqfetcher.DbSourceProxy;\r
27 \r
28 import java.util.ArrayList;\r
29 import java.util.Enumeration;\r
30 import java.util.List;\r
31 import java.util.Vector;\r
32 \r
33 /**\r
34  * This is the the concrete implementation of the sequence retrieval interface\r
35  * and abstract class in jalview.ws.seqfetcher. This implements the run-time\r
36  * discovery of sequence database clients, and provides a hardwired main for\r
37  * testing all registered handlers.\r
38  * \r
39  */\r
40 public class SequenceFetcher extends ASequenceFetcher\r
41 {\r
42   /**\r
43    * Thread safe construction of database proxies TODO: extend to a configurable\r
44    * database plugin mechanism where classes are instantiated by reflection and\r
45    * queried for their DbRefSource and version association.\r
46    * \r
47    */\r
48   public SequenceFetcher()\r
49   {\r
50     addDBRefSourceImpl(jalview.ws.dbsources.EmblSource.class);\r
51     addDBRefSourceImpl(jalview.ws.dbsources.EmblCdsSouce.class);\r
52     addDBRefSourceImpl(jalview.ws.dbsources.Uniprot.class);\r
53     addDBRefSourceImpl(jalview.ws.dbsources.UnprotName.class);\r
54     addDBRefSourceImpl(jalview.ws.dbsources.Pdb.class);\r
55     addDBRefSourceImpl(jalview.ws.dbsources.PfamFull.class);\r
56     addDBRefSourceImpl(jalview.ws.dbsources.PfamSeed.class); // ensures Seed\r
57     // alignment is\r
58     // 'default' for\r
59     // PFAM\r
60     addDBRefSourceImpl(jalview.ws.dbsources.RfamFull.class);\r
61     addDBRefSourceImpl(jalview.ws.dbsources.RfamSeed.class);\r
62     registerDasSequenceSources();\r
63   }\r
64 \r
65   /**\r
66    * return an ordered list of database sources suitable for using in a GUI\r
67    * element\r
68    */\r
69   public String[] getOrderedSupportedSources()\r
70   {\r
71     String[] srcs = this.getSupportedDb();\r
72     ArrayList dassrc = new ArrayList(), nondas = new ArrayList();\r
73     for (int i = 0; i < srcs.length; i++)\r
74     {\r
75       for (DbSourceProxy dbs : getSourceProxy(srcs[i]))\r
76       {\r
77         String nm = dbs.getDbName();\r
78         if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)\r
79         {\r
80           if (nm.startsWith("das:"))\r
81           {\r
82             nm = nm.substring(4);\r
83           }\r
84           dassrc.add(new String[]\r
85           { srcs[i], nm.toUpperCase() });\r
86         }\r
87         else\r
88         {\r
89           nondas.add(new String[]\r
90           { srcs[i], nm.toUpperCase() });\r
91         }\r
92       }\r
93     }\r
94     Object[] sorted = nondas.toArray();\r
95     String[] tosort = new String[sorted.length];\r
96     nondas.clear();\r
97     for (int j = 0; j < sorted.length; j++)\r
98     {\r
99       tosort[j] = ((String[]) sorted[j])[1];\r
100     }\r
101     jalview.util.QuickSort.sort(tosort, sorted);\r
102     int i = 0;\r
103     // construct array with all sources listed\r
104     srcs = new String[sorted.length + dassrc.size()];\r
105     for (int j = sorted.length - 1; j >= 0; j--, i++)\r
106     {\r
107       srcs[i] = ((String[]) sorted[j])[0];\r
108       sorted[j] = null;\r
109     }\r
110 \r
111     sorted = dassrc.toArray();\r
112     tosort = new String[sorted.length];\r
113     dassrc.clear();\r
114     for (int j = 0; j < sorted.length; j++)\r
115     {\r
116       tosort[j] = ((String[]) sorted[j])[1];\r
117     }\r
118     jalview.util.QuickSort.sort(tosort, sorted);\r
119     for (int j = sorted.length - 1; j >= 0; j--, i++)\r
120     {\r
121       srcs[i] = ((String[]) sorted[j])[0];\r
122       sorted[j] = null;\r
123     }\r
124     return srcs;\r
125   }\r
126 \r
127   /**\r
128    * simple run method to test dbsources.\r
129    * \r
130    * @param argv\r
131    */\r
132   public static void main(String[] argv)\r
133   {\r
134     AlignmentI ds = null;\r
135     Vector noProds = new Vector();\r
136     String usage = "SequenceFetcher.main [<DBNAME> <ACCNO>]\n"\r
137             + "With no arguments, all DbSources will be queried with their test Accession number.\n"\r
138             + "If given two arguments, SequenceFetcher will try to find the DbFetcher corresponding to <DBNAME> and retrieve <ACCNO> from it.";\r
139     if (argv != null && argv.length > 0)\r
140     {\r
141       List<DbSourceProxy> sps = new SequenceFetcher()\r
142               .getSourceProxy(argv[0]);\r
143 \r
144       if (sps != null)\r
145       {\r
146         for (DbSourceProxy sp : sps)\r
147         {\r
148           AlignmentI al = null;\r
149           try\r
150           {\r
151             al = sp.getSequenceRecords(argv[1]);\r
152           } catch (Exception e)\r
153           {\r
154             e.printStackTrace();\r
155             System.err.println("Error when retrieving " + argv[1]\r
156                     + " from " + argv[0] + "\nUsage: " + usage);\r
157           }\r
158           SequenceI[] prod = al.getSequencesArray();\r
159           if (al != null)\r
160           {\r
161             for (int p = 0; p < prod.length; p++)\r
162             {\r
163               System.out.println("Prod " + p + ": "\r
164                       + prod[p].getDisplayId(true) + " : "\r
165                       + prod[p].getDescription());\r
166             }\r
167           }\r
168         }\r
169         return;\r
170       }\r
171       else\r
172       {\r
173         System.err.println("Can't resolve " + argv[0]\r
174                 + " as a database name. Allowed values are :\n"\r
175                 + new SequenceFetcher().getSupportedDb());\r
176       }\r
177       System.out.println(usage);\r
178       return;\r
179     }\r
180     ASequenceFetcher sfetcher = new SequenceFetcher();\r
181     String[] dbSources = sfetcher.getSupportedDb();\r
182     for (int dbsource = 0; dbsource < dbSources.length; dbsource++)\r
183     {\r
184       String db = dbSources[dbsource];\r
185       // skip me\r
186       if (db.equals(DBRefSource.PDB))\r
187         continue;\r
188       for (DbSourceProxy sp : sfetcher.getSourceProxy(db))\r
189       {\r
190         System.out.println("Source: " + sp.getDbName() + " (" + db\r
191                 + "): retrieving test:" + sp.getTestQuery());\r
192         AlignmentI al = null;\r
193         try\r
194         {\r
195           al = sp.getSequenceRecords(sp.getTestQuery());\r
196           if (al != null && al.getHeight() > 0\r
197                   && sp.getDbSourceProperties() != null)\r
198           {\r
199             boolean dna = sp.getDbSourceProperties().containsKey(\r
200                     DBRefSource.DNACODINGSEQDB)\r
201                     || sp.getDbSourceProperties().containsKey(\r
202                             DBRefSource.DNASEQDB)\r
203                     || sp.getDbSourceProperties().containsKey(\r
204                             DBRefSource.CODINGSEQDB);\r
205             // try and find products\r
206             String types[] = jalview.analysis.CrossRef\r
207                     .findSequenceXrefTypes(dna, al.getSequencesArray());\r
208             if (types != null)\r
209             {\r
210               System.out.println("Xref Types for: "\r
211                       + (dna ? "dna" : "prot"));\r
212               for (int t = 0; t < types.length; t++)\r
213               {\r
214                 System.out.println("Type: " + types[t]);\r
215                 SequenceI[] prod = jalview.analysis.CrossRef\r
216                         .findXrefSequences(al.getSequencesArray(), dna,\r
217                                 types[t]).getSequencesArray();\r
218                 System.out.println("Found "\r
219                         + ((prod == null) ? "no" : "" + prod.length)\r
220                         + " products");\r
221                 if (prod != null)\r
222                 {\r
223                   for (int p = 0; p < prod.length; p++)\r
224                   {\r
225                     System.out.println("Prod " + p + ": "\r
226                             + prod[p].getDisplayId(true));\r
227                   }\r
228                 }\r
229               }\r
230             }\r
231             else\r
232             {\r
233               noProds.addElement((dna ? new Object[]\r
234               { al, al } : new Object[]\r
235               { al }));\r
236             }\r
237 \r
238           }\r
239         } catch (Exception ex)\r
240         {\r
241           System.out.println("ERROR:Failed to retrieve test query.");\r
242           ex.printStackTrace(System.out);\r
243         }\r
244 \r
245         if (al == null)\r
246         {\r
247           System.out.println("ERROR:No alignment retrieved.");\r
248           StringBuffer raw = sp.getRawRecords();\r
249           if (raw != null)\r
250             System.out.println(raw.toString());\r
251           else\r
252             System.out.println("ERROR:No Raw results.");\r
253         }\r
254         else\r
255         {\r
256           System.out.println("Retrieved " + al.getHeight() + " sequences.");\r
257           for (int s = 0; s < al.getHeight(); s++)\r
258           {\r
259             SequenceI sq = al.getSequenceAt(s);\r
260             while (sq.getDatasetSequence() != null)\r
261             {\r
262               sq = sq.getDatasetSequence();\r
263 \r
264             }\r
265             if (ds == null)\r
266             {\r
267               ds = new Alignment(new SequenceI[]\r
268               { sq });\r
269 \r
270             }\r
271             else\r
272             {\r
273               ds.addSequence(sq);\r
274             }\r
275           }\r
276         }\r
277         System.out.flush();\r
278         System.err.flush();\r
279 \r
280       }\r
281       if (noProds.size() > 0)\r
282       {\r
283         Enumeration ts = noProds.elements();\r
284         while (ts.hasMoreElements())\r
285 \r
286         {\r
287           Object[] typeSq = (Object[]) ts.nextElement();\r
288           boolean dna = (typeSq.length > 1);\r
289           AlignmentI al = (AlignmentI) typeSq[0];\r
290           System.out.println("Trying getProducts for "\r
291                   + al.getSequenceAt(0).getDisplayId(true));\r
292           System.out.println("Search DS Xref for: "\r
293                   + (dna ? "dna" : "prot"));\r
294           // have a bash at finding the products amongst all the retrieved\r
295           // sequences.\r
296           SequenceI[] seqs = al.getSequencesArray();\r
297           Alignment prodal = jalview.analysis.CrossRef.findXrefSequences(\r
298                   seqs, dna, null, ds);\r
299           System.out.println("Found "\r
300                   + ((prodal == null) ? "no" : "" + prodal.getHeight())\r
301                   + " products");\r
302           if (prodal != null)\r
303           {\r
304             SequenceI[] prod = prodal.getSequencesArray(); // note\r
305             // should\r
306             // test\r
307             // rather\r
308             // than\r
309             // throw\r
310             // away\r
311             // codon\r
312             // mapping\r
313             // (if\r
314             // present)\r
315             for (int p = 0; p < prod.length; p++)\r
316             {\r
317               System.out.println("Prod " + p + ": "\r
318                       + prod[p].getDisplayId(true));\r
319             }\r
320           }\r
321         }\r
322 \r
323       }\r
324 \r
325     }\r
326   }\r
327 \r
328   /**\r
329    * query the currently defined DAS source registry for sequence sources and\r
330    * add a DasSequenceSource instance for each source to the SequenceFetcher\r
331    * source list.\r
332    */\r
333   public void registerDasSequenceSources()\r
334   {\r
335     // TODO: define a context as a registry provider (either desktop,\r
336     // jalview.bin.cache, or something else).\r
337     for (jalviewSourceI source : jalview.bin.Cache.getDasSourceRegistry()\r
338             .getSources())\r
339     {\r
340       if (source.isSequenceSource())\r
341       {\r
342         List<DbSourceProxy> dassources = source.getSequenceSourceProxies();\r
343         for (DbSourceProxy seqsrc : dassources)\r
344         {\r
345           addDbRefSourceImpl(seqsrc);\r
346         }\r
347       }\r
348     }\r
349   }\r
350 }\r