JAL-1855 dbfetch from /ena_sequence/, /ena_coding/
[jalview.git] / src / jalview / ws / ebi / EBIFetchClient.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.ebi;
22
23 import jalview.datamodel.DBRefSource;
24 import jalview.util.MessageManager;
25
26 import java.io.BufferedInputStream;
27 import java.io.BufferedReader;
28 import java.io.File;
29 import java.io.FileOutputStream;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.net.URL;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.StringTokenizer;
36
37 /**
38  * DOCUMENT ME!
39  * 
40  * @author $author$
41  * @version $Revision$
42  */
43 public class EBIFetchClient
44 {
45   String format = "default";
46
47   String style = "raw";
48
49   /**
50    * Creates a new EBIFetchClient object.
51    */
52   public EBIFetchClient()
53   {
54   }
55
56   /**
57    * DOCUMENT ME!
58    * 
59    * @return DOCUMENT ME!
60    */
61   public String[] getSupportedDBs()
62   {
63     // TODO - implement rest call for dbfetch getSupportedDBs
64     throw new Error(MessageManager.getString("error.not_yet_implemented"));
65   }
66
67   /**
68    * DOCUMENT ME!
69    * 
70    * @return DOCUMENT ME!
71    */
72   public String[] getSupportedFormats()
73   {
74     // TODO - implement rest call for dbfetch getSupportedFormats
75     throw new Error(MessageManager.getString("error.not_yet_implemented"));
76   }
77
78   /**
79    * DOCUMENT ME!
80    * 
81    * @return DOCUMENT ME!
82    */
83   public String[] getSupportedStyles()
84   {
85     // TODO - implement rest call for dbfetch getSupportedStyles
86     throw new Error(MessageManager.getString("error.not_yet_implemented"));
87   }
88
89   /**
90    * Send an HTTP fetch request to EBI and save the reply in a temporary file.
91    * 
92    * @param ids
93    *          the query formatted as db:query1;query2;query3
94    * @param format
95    *          the format wanted
96    * @param s
97    *          - unused parameter
98    * @return the file holding the response
99    * @throws OutOfMemoryError
100    */
101   public File fetchDataAsFile(String ids, String format, String s)
102           throws OutOfMemoryError
103   {
104     File outFile = null;
105     try
106     {
107       outFile = File.createTempFile("jalview", ".xml");
108       outFile.deleteOnExit();
109       fetchData(ids, format, s, outFile);
110       if (outFile.length() == 0)
111       {
112         outFile.delete();
113         return null;
114       }
115     } catch (Exception ex)
116     {
117     }
118     return outFile;
119   }
120
121   /**
122    * Single DB multiple record retrieval
123    * 
124    * @param ids
125    *          db:query1;query2;query3
126    * @param format
127    *          raw/xml
128    * @param s
129    *          not used - remove?
130    * 
131    * @return Raw string array result of query set
132    */
133   public String[] fetchData(String ids, String format, String s)
134           throws OutOfMemoryError
135   {
136     return fetchData(ids, format, s, null);
137   }
138
139   String[] fetchData(String ids, String f, String s, File outFile)
140           throws OutOfMemoryError
141   {
142     // Need to split
143     // ids of the form uniprot:25KD_SARPE;ADHR_DROPS;
144     String[] rslts = new String[0];
145     StringTokenizer queries = new StringTokenizer(ids, ";");
146     String db = null;
147     StringBuffer querystring = null;
148     int nq = 0;
149     while (queries.hasMoreTokens())
150     {
151       String query = queries.nextToken();
152       int p;
153       if ((p = query.indexOf(':')) > -1)
154       {
155         db = query.substring(0, p);
156         query = query.substring(p + 1);
157       }
158       if (querystring == null)
159       {
160         querystring = new StringBuffer(query);
161         nq++;
162       }
163       else
164       {
165         querystring.append("," + query);
166         nq++;
167       }
168     }
169     if (db == null)
170     {
171       System.err.println("Invalid Query string : '" + ids
172               + "'\nShould be of form 'dbname:q1;q2;q3;q4'");
173       return null;
174     }
175     String[] rslt = fetchBatch(querystring.toString(), db, f, s, outFile);
176     if (rslt != null)
177     {
178       String[] nrslts = new String[rslt.length + rslts.length];
179       System.arraycopy(rslts, 0, nrslts, 0, rslts.length);
180       System.arraycopy(rslt, 0, nrslts, rslts.length, rslt.length);
181       rslts = nrslts;
182     }
183
184     return (rslts.length == 0 ? null : rslts);
185   }
186
187   public String[] fetchBatch(String ids, String dbPath, String format, String s,
188           File outFile) throws OutOfMemoryError
189   {
190     // long time = System.currentTimeMillis();
191     /*
192      * JAL-1855 dbfetch from ena_sequence, ena_coding
193      */
194     if (dbPath.equalsIgnoreCase(DBRefSource.EMBL))
195     {
196       dbPath = "ena_sequence";
197     }
198     else if (dbPath.equalsIgnoreCase(DBRefSource.EMBLCDS))
199     {
200       dbPath = "ena_coding";
201     }
202
203     try
204     {
205       URL rcall = new URL("http://www.ebi.ac.uk/Tools/dbfetch/dbfetch/"
206               + dbPath.toLowerCase() + "/" + ids.toLowerCase()
207               + (format != null ? "/" + format : ""));
208
209       InputStream is = new BufferedInputStream(rcall.openStream());
210       if (outFile != null)
211       {
212         FileOutputStream fio = new FileOutputStream(outFile);
213         byte[] bb = new byte[32 * 1024];
214         int l;
215         while ((l = is.read(bb)) > 0)
216         {
217           fio.write(bb, 0, l);
218         }
219         fio.close();
220         is.close();
221       }
222       else
223       {
224         BufferedReader br = new BufferedReader(new InputStreamReader(is));
225         String rtn;
226         List<String> arl = new ArrayList<String>();
227         while ((rtn = br.readLine()) != null)
228         {
229           arl.add(rtn);
230         }
231         return arl.toArray(new String[arl.size()]);
232       }
233     } catch (OutOfMemoryError er)
234     {
235
236       System.out.println("OUT OF MEMORY DOWNLOADING QUERY FROM " + dbPath
237               + ":\n" + ids);
238       throw er;
239     } catch (Exception ex)
240     {
241       if (ex.getMessage().startsWith(
242               "uk.ac.ebi.jdbfetch.exceptions.DbfNoEntryFoundException"))
243       {
244         return null;
245       }
246       System.err.println("Unexpected exception when retrieving from "
247               + dbPath
248               + "\nQuery was : '" + ids + "'");
249       ex.printStackTrace(System.err);
250       return null;
251     } finally
252     {
253       // System.err.println("EBIFetch took " + (System.currentTimeMillis() -
254       // time) + " ms");
255     }
256     return null;
257   }
258 }