7752e9c9c18bfd2bf0218383c1d9d7739584a1f1
[jalview.git] / src / jalview / ext / ensembl / EnsemblRestClient.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.ext.ensembl;
22
23 import jalview.io.DataSourceType;
24 import jalview.io.FileParse;
25 import jalview.util.StringUtils;
26
27 import java.io.BufferedReader;
28 import java.io.DataOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.net.HttpURLConnection;
33 import java.net.MalformedURLException;
34 import java.net.URL;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38
39 import javax.ws.rs.HttpMethod;
40
41 import org.json.simple.JSONArray;
42 import org.json.simple.JSONObject;
43 import org.json.simple.parser.JSONParser;
44
45 /**
46  * Base class for Ensembl REST service clients
47  * 
48  * @author gmcarstairs
49  */
50 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
51 {
52   private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
53
54   private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
55
56   /*
57    * update these constants when Jalview has been checked / updated for
58    * changes to Ensembl REST API (ref JAL-2105)
59    * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
60    * @see http://rest.ensembl.org/info/rest?content-type=application/json
61    */
62   private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "5.0";
63
64   private static final String LATEST_ENSEMBL_REST_VERSION = "5.0";
65
66   private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
67
68   private static Map<String, EnsemblInfo> domainData;
69
70   // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
71   private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
72
73   private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
74
75   private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
76
77   static
78   {
79     domainData = new HashMap<String, EnsemblInfo>();
80     domainData.put(ENSEMBL_REST,
81             new EnsemblInfo(ENSEMBL_REST, LATEST_ENSEMBL_REST_VERSION));
82     domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
83             ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
84   }
85
86   protected volatile boolean inProgress = false;
87
88   /**
89    * Default constructor to use rest.ensembl.org
90    */
91   public EnsemblRestClient()
92   {
93     this(ENSEMBL_REST);
94   }
95
96   /**
97    * Constructor given the target domain to fetch data from
98    * 
99    * @param d
100    */
101   public EnsemblRestClient(String d)
102   {
103     setDomain(d);
104   }
105
106   @Override
107   public boolean queryInProgress()
108   {
109     return inProgress;
110   }
111
112   @Override
113   public StringBuffer getRawRecords()
114   {
115     return null;
116   }
117
118   /**
119    * Returns the URL for the client http request
120    * 
121    * @param ids
122    * @return
123    * @throws MalformedURLException
124    */
125   protected abstract URL getUrl(List<String> ids)
126           throws MalformedURLException;
127
128   /**
129    * Returns true if client uses GET method, false if it uses POST
130    * 
131    * @return
132    */
133   protected abstract boolean useGetRequest();
134
135   /**
136    * Return the desired value for the Content-Type request header
137    * 
138    * @param multipleIds
139    * 
140    * @return
141    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
142    */
143   protected abstract String getRequestMimeType(boolean multipleIds);
144
145   /**
146    * Return the desired value for the Accept request header
147    * 
148    * @return
149    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
150    */
151   protected abstract String getResponseMimeType();
152
153   /**
154    * Checks Ensembl's REST 'ping' endpoint, and returns true if response
155    * indicates available, else false
156    * 
157    * @see http://rest.ensembl.org/documentation/info/ping
158    * @return
159    */
160   private boolean checkEnsembl()
161   {
162     BufferedReader br = null;
163     try
164     {
165       // note this format works for both ensembl and ensemblgenomes
166       // info/ping.json works for ensembl only (March 2016)
167       URL ping = new URL(
168               getDomain() + "/info/ping?content-type=application/json");
169
170       /*
171        * expect {"ping":1} if ok
172        * if ping takes more than 2 seconds to respond, treat as if unavailable
173        */
174       br = getHttpResponse(ping, null, 2 * 1000);
175       if (br == null)
176       {
177         // error reponse status
178         return false;
179       }
180       JSONParser jp = new JSONParser();
181       JSONObject val = (JSONObject) jp.parse(br);
182       String pingString = val.get("ping").toString();
183       return pingString != null;
184     } catch (Throwable t)
185     {
186       System.err.println(
187               "Error connecting to " + PING_URL + ": " + t.getMessage());
188     } finally
189     {
190       if (br != null)
191       {
192         try
193         {
194           br.close();
195         } catch (IOException e)
196         {
197           // ignore
198         }
199       }
200     }
201     return false;
202   }
203
204   /**
205    * returns a reader to a Fasta response from the Ensembl sequence endpoint
206    * 
207    * @param ids
208    * @return
209    * @throws IOException
210    */
211   protected FileParse getSequenceReader(List<String> ids) throws IOException
212   {
213     URL url = getUrl(ids);
214
215     BufferedReader reader = getHttpResponse(url, ids);
216     if (reader == null)
217     {
218       // request failed
219       return null;
220     }
221     FileParse fp = new FileParse(reader, url.toString(),
222             DataSourceType.URL);
223     return fp;
224   }
225
226   /**
227    * Gets a reader to the HTTP response, using the default read timeout of 5
228    * minutes
229    * 
230    * @param url
231    * @param ids
232    * @return
233    * @throws IOException
234    */
235   protected BufferedReader getHttpResponse(URL url, List<String> ids)
236           throws IOException
237   {
238     return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
239   }
240
241   /**
242    * Writes the HTTP request and gets the response as a reader.
243    * 
244    * @param url
245    * @param ids
246    *          written as Json POST body if more than one
247    * @param readTimeout
248    *          in milliseconds
249    * @return
250    * @throws IOException
251    *           if response code was not 200, or other I/O error
252    */
253   protected BufferedReader getHttpResponse(URL url, List<String> ids,
254           int readTimeout) throws IOException
255   {
256     // long now = System.currentTimeMillis();
257     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
258
259     /*
260      * POST method allows multiple queries in one request; it is supported for
261      * sequence queries, but not for overlap
262      */
263     boolean multipleIds = ids != null && ids.size() > 1;
264     connection.setRequestMethod(
265             multipleIds ? HttpMethod.POST : HttpMethod.GET);
266     connection.setRequestProperty("Content-Type",
267             getRequestMimeType(multipleIds));
268     connection.setRequestProperty("Accept", getResponseMimeType());
269
270     connection.setUseCaches(false);
271     connection.setDoInput(true);
272     connection.setDoOutput(multipleIds);
273
274     connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
275     connection.setReadTimeout(readTimeout);
276
277     if (multipleIds)
278     {
279       writePostBody(connection, ids);
280     }
281
282     int responseCode = connection.getResponseCode();
283
284     if (responseCode != 200)
285     {
286       /*
287        * note: a GET request for an invalid id returns an error code e.g. 415
288        * but POST request returns 200 and an empty Fasta response 
289        */
290       System.err.println("Response code " + responseCode + " for " + url);
291       return null;
292     }
293     // get content
294     InputStream response = connection.getInputStream();
295
296     // System.out.println(getClass().getName() + " took "
297     // + (System.currentTimeMillis() - now) + "ms to fetch");
298
299     checkRateLimits(connection);
300
301     BufferedReader reader = null;
302     reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
303     return reader;
304   }
305
306   /**
307    * Inspect response headers for any sign of server overload and respect any
308    * 'retry-after' directive
309    * 
310    * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
311    * @param connection
312    */
313   void checkRateLimits(HttpURLConnection connection)
314   {
315     // number of requests allowed per time interval:
316     // String limit = connection.getHeaderField("X-RateLimit-Limit");
317     // length of quota time interval in seconds:
318     // String period = connection.getHeaderField("X-RateLimit-Period");
319     // seconds remaining until usage quota is reset:
320     // String reset = connection.getHeaderField("X-RateLimit-Reset");
321     // number of requests remaining from quota for current period:
322     // String remaining = connection.getHeaderField("X-RateLimit-Remaining");
323     // number of seconds to wait before retrying (if remaining == 0)
324     String retryDelay = connection.getHeaderField("Retry-After");
325
326     // to test:
327     // retryDelay = "5";
328
329     EnsemblInfo info = domainData.get(getDomain());
330     if (retryDelay != null)
331     {
332       System.err.println("Ensembl REST service rate limit exceeded, wait "
333               + retryDelay + " seconds before retrying");
334       try
335       {
336         info.retryAfter = System.currentTimeMillis()
337                 + (1000 * Integer.valueOf(retryDelay));
338       } catch (NumberFormatException e)
339       {
340         System.err
341                 .println("Unexpected value for Retry-After: " + retryDelay);
342       }
343     }
344     else
345     {
346       info.retryAfter = 0;
347       // debug:
348       // System.out.println(String.format(
349       // "%s Ensembl requests remaining of %s (reset in %ss)",
350       // remaining, limit, reset));
351     }
352   }
353
354   /**
355    * Rechecks if Ensembl is responding, unless the last check was successful and
356    * the retest interval has not yet elapsed. Returns true if Ensembl is up,
357    * else false. Also retrieves and saves the current version of Ensembl data
358    * and REST services at intervals.
359    * 
360    * @return
361    */
362   protected boolean isEnsemblAvailable()
363   {
364     EnsemblInfo info = domainData.get(getDomain());
365
366     long now = System.currentTimeMillis();
367
368     /*
369      * check if we are waiting for 'Retry-After' to expire
370      */
371     if (info.retryAfter > now)
372     {
373       System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
374               + " secs to wait before retrying Ensembl");
375       return false;
376     }
377     else
378     {
379       info.retryAfter = 0;
380     }
381
382     /*
383      * recheck if Ensembl is up if it was down, or the recheck period has elapsed
384      */
385     boolean retestAvailability = (now
386             - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
387     if (!info.restAvailable || retestAvailability)
388     {
389       info.restAvailable = checkEnsembl();
390       info.lastAvailableCheckTime = now;
391     }
392
393     /*
394      * refetch Ensembl versions if the recheck period has elapsed
395      */
396     boolean refetchVersion = (now
397             - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
398     if (refetchVersion)
399     {
400       checkEnsemblRestVersion();
401       checkEnsemblDataVersion();
402       info.lastVersionCheckTime = now;
403     }
404
405     return info.restAvailable;
406   }
407
408   /**
409    * Constructs, writes and flushes the POST body of the request, containing the
410    * query ids in JSON format
411    * 
412    * @param connection
413    * @param ids
414    * @throws IOException
415    */
416   protected void writePostBody(HttpURLConnection connection,
417           List<String> ids) throws IOException
418   {
419     boolean first;
420     StringBuilder postBody = new StringBuilder(64);
421     postBody.append("{\"ids\":[");
422     first = true;
423     for (String id : ids)
424     {
425       if (!first)
426       {
427         postBody.append(",");
428       }
429       first = false;
430       postBody.append("\"");
431       postBody.append(id.trim());
432       postBody.append("\"");
433     }
434     postBody.append("]}");
435     byte[] thepostbody = postBody.toString().getBytes();
436     connection.setRequestProperty("Content-Length",
437             Integer.toString(thepostbody.length));
438     DataOutputStream wr = new DataOutputStream(
439             connection.getOutputStream());
440     wr.write(thepostbody);
441     wr.flush();
442     wr.close();
443   }
444
445   /**
446    * Fetches and checks Ensembl's REST version number
447    * 
448    * @return
449    */
450   private void checkEnsemblRestVersion()
451   {
452     EnsemblInfo info = domainData.get(getDomain());
453
454     JSONParser jp = new JSONParser();
455     URL url = null;
456     try
457     {
458       url = new URL(
459               getDomain() + "/info/rest?content-type=application/json");
460       BufferedReader br = getHttpResponse(url, null);
461       if (br == null)
462       {
463         return;
464       }
465       JSONObject val = (JSONObject) jp.parse(br);
466       String version = val.get("release").toString();
467       String majorVersion = version.substring(0, version.indexOf("."));
468       String expected = info.expectedRestVersion;
469       String expectedMajorVersion = expected.substring(0,
470               expected.indexOf("."));
471       info.restMajorVersionMismatch = false;
472       try
473       {
474         /*
475          * if actual REST major version is ahead of what we expect,
476          * record this in case we want to warn the user
477          */
478         if (Float.valueOf(majorVersion) > Float
479                 .valueOf(expectedMajorVersion))
480         {
481           info.restMajorVersionMismatch = true;
482         }
483       } catch (NumberFormatException e)
484       {
485         System.err.println("Error in REST version: " + e.toString());
486       }
487
488       /*
489        * check if REST version is later than what Jalview has tested against,
490        * if so warn; we don't worry if it is earlier (this indicates Jalview has
491        * been tested in advance against the next pending REST version)
492        */
493       boolean laterVersion = StringUtils.compareVersions(version,
494               expected) == 1;
495       if (laterVersion)
496       {
497         System.err.println(String.format(
498                 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
499                 getDbSource(), expected, version, REST_CHANGE_LOG));
500       }
501       info.restVersion = version;
502     } catch (Throwable t)
503     {
504       System.err.println(
505               "Error checking Ensembl REST version: " + t.getMessage());
506     }
507   }
508
509   public boolean isRestMajorVersionMismatch()
510   {
511     return domainData.get(getDomain()).restMajorVersionMismatch;
512   }
513
514   /**
515    * Fetches and checks Ensembl's data version number
516    * 
517    * @return
518    */
519   private void checkEnsemblDataVersion()
520   {
521     JSONParser jp = new JSONParser();
522     URL url = null;
523     try
524     {
525       url = new URL(
526               getDomain() + "/info/data?content-type=application/json");
527       BufferedReader br = getHttpResponse(url, null);
528       if (br != null)
529       {
530         JSONObject val = (JSONObject) jp.parse(br);
531         JSONArray versions = (JSONArray) val.get("releases");
532         domainData.get(getDomain()).dataVersion = versions.get(0)
533                 .toString();
534       }
535     } catch (Throwable t)
536     {
537       System.err.println(
538               "Error checking Ensembl data version: " + t.getMessage());
539     }
540   }
541
542   public String getEnsemblDataVersion()
543   {
544     return domainData.get(getDomain()).dataVersion;
545   }
546
547   @Override
548   public String getDbVersion()
549   {
550     return getEnsemblDataVersion();
551   }
552
553 }