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