JAL-1432 updated copyright notices
[jalview.git] / src / jalview / ws / ebi / EBIFetchClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3  * Copyright (C) 2014 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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 package jalview.ws.ebi;
20
21 import java.io.BufferedInputStream;
22 import java.io.BufferedReader;
23 import java.io.File;
24 import java.io.FileOutputStream;
25 import java.io.InputStreamReader;
26 import java.net.URL;
27 import java.util.ArrayList;
28 import java.util.StringTokenizer;
29
30 /**
31  * DOCUMENT ME!
32  * 
33  * @author $author$
34  * @version $Revision$
35  */
36 public class EBIFetchClient
37 {
38   String format = "default";
39
40   String style = "raw";
41
42   /**
43    * Creates a new EBIFetchClient object.
44    */
45   public EBIFetchClient()
46   {
47   }
48
49   /**
50    * DOCUMENT ME!
51    * 
52    * @return DOCUMENT ME!
53    */
54   public String[] getSupportedDBs()
55   {
56     // TODO - implement rest call for dbfetch getSupportedDBs
57     throw new Error("Not yet implemented");
58   }
59
60   /**
61    * DOCUMENT ME!
62    * 
63    * @return DOCUMENT ME!
64    */
65   public String[] getSupportedFormats()
66   {
67     // TODO - implement rest call for dbfetch getSupportedFormats
68     throw new Error("Not yet implemented");
69   }
70
71   /**
72    * DOCUMENT ME!
73    * 
74    * @return DOCUMENT ME!
75    */
76   public String[] getSupportedStyles()
77   {
78     // TODO - implement rest call for dbfetch getSupportedStyles
79     throw new Error("Not yet implemented");
80   }
81
82   public File fetchDataAsFile(String ids, String f, String s)
83           throws OutOfMemoryError
84   {
85     File outFile = null;
86     try
87     {
88       outFile = File.createTempFile("jalview", ".xml");
89       outFile.deleteOnExit();
90       fetchData(ids, f, s, outFile);
91       if (outFile.length() == 0)
92       {
93         outFile.delete();
94         return null;
95       }
96     } catch (Exception ex)
97     {
98     }
99     return outFile;
100   }
101
102   /**
103    * Single DB multiple record retrieval
104    * 
105    * @param ids
106    *          db:query1;query2;query3
107    * @param f
108    *          raw/xml
109    * @param s
110    *          ?
111    * 
112    * @return Raw string array result of query set
113    */
114   public String[] fetchData(String ids, String f, String s)
115           throws OutOfMemoryError
116   {
117     return fetchData(ids, f, s, null);
118   }
119
120   public String[] fetchData(String ids, String f, String s, File outFile)
121           throws OutOfMemoryError
122   {
123     // Need to split
124     // ids of the form uniprot:25KD_SARPE;ADHR_DROPS;
125     String[] rslts = new String[0];
126     StringTokenizer queries = new StringTokenizer(ids, ";");
127     String db = null;
128     StringBuffer querystring = null;
129     int nq = 0;
130     while (queries.hasMoreTokens())
131     {
132       String query = queries.nextToken();
133       int p;
134       if ((p = query.indexOf(':')) > -1)
135       {
136         db = query.substring(0, p);
137         query = query.substring(p + 1);
138       }
139       if (querystring == null)
140       {
141         querystring = new StringBuffer(query);
142         nq++;
143       }
144       else
145       {
146         querystring.append("," + query);
147         nq++;
148       }
149     }
150     if (db == null)
151     {
152       System.err.println("Invalid Query string : '" + ids
153               + "'\nShould be of form 'dbname:q1;q2;q3;q4'");
154       return null;
155     }
156     String[] rslt = fetchBatch(querystring.toString(), db, f, s, outFile);
157     if (rslt != null)
158     {
159       String[] nrslts = new String[rslt.length + rslts.length];
160       System.arraycopy(rslts, 0, nrslts, 0, rslts.length);
161       System.arraycopy(rslt, 0, nrslts, rslts.length, rslt.length);
162       rslts = nrslts;
163     }
164
165     return (rslts.length == 0 ? null : rslts);
166   }
167
168   public String[] fetchBatch(String ids, String db, String f, String s,
169           File outFile) throws OutOfMemoryError
170   {
171     long time = System.currentTimeMillis();
172     // max 200 ids can be added at one time
173     try
174     {
175       URL rcall = new URL("http://www.ebi.ac.uk/Tools/dbfetch/dbfetch/"
176               + db.toLowerCase() + "/" + ids.toLowerCase()
177               + (f != null ? "/" + f : ""));
178
179       BufferedInputStream is = new BufferedInputStream(rcall.openStream());
180       if (outFile != null)
181       {
182         FileOutputStream fio = new FileOutputStream(outFile);
183         byte[] bb = new byte[32 * 1024];
184         int l;
185         while ((l = is.read(bb)) > 0)
186         {
187           fio.write(bb, 0, l);
188         }
189         fio.close();
190         is.close();
191       }
192       else
193       {
194         BufferedReader br = new BufferedReader(new InputStreamReader(is));
195         String rtn;
196         ArrayList<String> arl = new ArrayList<String>();
197         while ((rtn = br.readLine()) != null)
198         {
199           arl.add(rtn);
200         }
201         return arl.toArray(new String[arl.size()]);
202       }
203     } catch (OutOfMemoryError er)
204     {
205
206       System.out.println("OUT OF MEMORY DOWNLOADING QUERY FROM " + db
207               + ":\n" + ids);
208       throw er;
209     } catch (Exception ex)
210     {
211       if (ex.getMessage().startsWith(
212               "uk.ac.ebi.jdbfetch.exceptions.DbfNoEntryFoundException"))
213       {
214         return null;
215       }
216       System.err.println("Unexpected exception when retrieving from " + db
217               + "\nQuery was : '" + ids + "'");
218       ex.printStackTrace(System.err);
219       return null;
220     } finally
221     {
222       //System.err.println("Took " + (System.currentTimeMillis() - time)
223       //        / 1000 + " secs for one call.");
224     }
225     return null;
226   }
227 }
228