JAL-2253 pull up constant, additional unit test
[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 = "6.0";
63
64   private static final String LATEST_ENSEMBL_REST_VERSION = "6.1";
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   protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
78
79   static
80   {
81     domainData = new HashMap<String, EnsemblInfo>();
82     domainData.put(ENSEMBL_REST,
83             new EnsemblInfo(ENSEMBL_REST, LATEST_ENSEMBL_REST_VERSION));
84     domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
85             ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
86   }
87
88   protected volatile boolean inProgress = false;
89
90   /**
91    * Default constructor to use rest.ensembl.org
92    */
93   public EnsemblRestClient()
94   {
95     this(ENSEMBL_REST);
96   }
97
98   /**
99    * Constructor given the target domain to fetch data from
100    * 
101    * @param d
102    */
103   public EnsemblRestClient(String d)
104   {
105     setDomain(d);
106   }
107
108   @Override
109   public boolean queryInProgress()
110   {
111     return inProgress;
112   }
113
114   @Override
115   public StringBuffer getRawRecords()
116   {
117     return null;
118   }
119
120   /**
121    * Returns the URL for the client http request
122    * 
123    * @param ids
124    * @return
125    * @throws MalformedURLException
126    */
127   protected abstract URL getUrl(List<String> ids)
128           throws MalformedURLException;
129
130   /**
131    * Returns true if client uses GET method, false if it uses POST
132    * 
133    * @return
134    */
135   protected abstract boolean useGetRequest();
136
137   /**
138    * Return the desired value for the Content-Type request header
139    * 
140    * @param multipleIds
141    * 
142    * @return
143    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
144    */
145   protected abstract String getRequestMimeType(boolean multipleIds);
146
147   /**
148    * Return the desired value for the Accept request header
149    * 
150    * @return
151    * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
152    */
153   protected abstract String getResponseMimeType();
154
155   /**
156    * Checks Ensembl's REST 'ping' endpoint, and returns true if response
157    * indicates available, else false
158    * 
159    * @see http://rest.ensembl.org/documentation/info/ping
160    * @return
161    */
162   private boolean checkEnsembl()
163   {
164     BufferedReader br = null;
165     try
166     {
167       // note this format works for both ensembl and ensemblgenomes
168       // info/ping.json works for ensembl only (March 2016)
169       URL ping = new URL(getDomain() + "/info/ping" + CONTENT_TYPE_JSON);
170
171       /*
172        * expect {"ping":1} if ok
173        * if ping takes more than 2 seconds to respond, treat as if unavailable
174        */
175       br = getHttpResponse(ping, null, 2 * 1000);
176       if (br == null)
177       {
178         // error reponse status
179         return false;
180       }
181       JSONParser jp = new JSONParser();
182       JSONObject val = (JSONObject) jp.parse(br);
183       String pingString = val.get("ping").toString();
184       return pingString != null;
185     } catch (Throwable t)
186     {
187       System.err.println(
188               "Error connecting to " + PING_URL + ": " + t.getMessage());
189     } finally
190     {
191       if (br != null)
192       {
193         try
194         {
195           br.close();
196         } catch (IOException e)
197         {
198           // ignore
199         }
200       }
201     }
202     return false;
203   }
204
205   /**
206    * returns a reader to a Fasta response from the Ensembl sequence endpoint
207    * 
208    * @param ids
209    * @return
210    * @throws IOException
211    */
212   protected FileParse getSequenceReader(List<String> ids) throws IOException
213   {
214     URL url = getUrl(ids);
215
216     BufferedReader reader = getHttpResponse(url, ids);
217     if (reader == null)
218     {
219       // request failed
220       return null;
221     }
222     FileParse fp = new FileParse(reader, url.toString(),
223             DataSourceType.URL);
224     return fp;
225   }
226
227   /**
228    * Gets a reader to the HTTP response, using the default read timeout of 5
229    * minutes
230    * 
231    * @param url
232    * @param ids
233    * @return
234    * @throws IOException
235    */
236   protected BufferedReader getHttpResponse(URL url, List<String> ids)
237           throws IOException
238   {
239     return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
240   }
241
242   /**
243    * Writes the HTTP request and gets the response as a reader.
244    * 
245    * @param url
246    * @param ids
247    *          written as Json POST body if more than one
248    * @param readTimeout
249    *          in milliseconds
250    * @return
251    * @throws IOException
252    *           if response code was not 200, or other I/O error
253    */
254   protected BufferedReader getHttpResponse(URL url, List<String> ids,
255           int readTimeout) throws IOException
256   {
257     // long now = System.currentTimeMillis();
258     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
259
260     /*
261      * POST method allows multiple queries in one request; it is supported for
262      * sequence queries, but not for overlap
263      */
264     boolean multipleIds = ids != null && ids.size() > 1;
265     connection.setRequestMethod(
266             multipleIds ? HttpMethod.POST : HttpMethod.GET);
267     connection.setRequestProperty("Content-Type",
268             getRequestMimeType(multipleIds));
269     connection.setRequestProperty("Accept", getResponseMimeType());
270
271     connection.setUseCaches(false);
272     connection.setDoInput(true);
273     connection.setDoOutput(multipleIds);
274
275     connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
276     connection.setReadTimeout(readTimeout);
277
278     if (multipleIds)
279     {
280       writePostBody(connection, ids);
281     }
282
283     int responseCode = connection.getResponseCode();
284
285     if (responseCode != 200)
286     {
287       /*
288        * note: a GET request for an invalid id returns an error code e.g. 415
289        * but POST request returns 200 and an empty Fasta response 
290        */
291       System.err.println("Response code " + responseCode + " for " + url);
292       return null;
293     }
294     // get content
295     InputStream response = connection.getInputStream();
296
297     // System.out.println(getClass().getName() + " took "
298     // + (System.currentTimeMillis() - now) + "ms to fetch");
299
300     checkRateLimits(connection);
301
302     BufferedReader reader = null;
303     reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
304     return reader;
305   }
306
307   /**
308    * Inspect response headers for any sign of server overload and respect any
309    * 'retry-after' directive
310    * 
311    * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
312    * @param connection
313    */
314   void checkRateLimits(HttpURLConnection connection)
315   {
316     // number of requests allowed per time interval:
317     // String limit = connection.getHeaderField("X-RateLimit-Limit");
318     // length of quota time interval in seconds:
319     // String period = connection.getHeaderField("X-RateLimit-Period");
320     // seconds remaining until usage quota is reset:
321     // String reset = connection.getHeaderField("X-RateLimit-Reset");
322     // number of requests remaining from quota for current period:
323     // String remaining = connection.getHeaderField("X-RateLimit-Remaining");
324     // number of seconds to wait before retrying (if remaining == 0)
325     String retryDelay = connection.getHeaderField("Retry-After");
326
327     // to test:
328     // retryDelay = "5";
329
330     EnsemblInfo info = domainData.get(getDomain());
331     if (retryDelay != null)
332     {
333       System.err.println("Ensembl REST service rate limit exceeded, wait "
334               + retryDelay + " seconds before retrying");
335       try
336       {
337         info.retryAfter = System.currentTimeMillis()
338                 + (1000 * Integer.valueOf(retryDelay));
339       } catch (NumberFormatException e)
340       {
341         System.err
342                 .println("Unexpected value for Retry-After: " + retryDelay);
343       }
344     }
345     else
346     {
347       info.retryAfter = 0;
348       // debug:
349       // System.out.println(String.format(
350       // "%s Ensembl requests remaining of %s (reset in %ss)",
351       // remaining, limit, reset));
352     }
353   }
354
355   /**
356    * Rechecks if Ensembl is responding, unless the last check was successful and
357    * the retest interval has not yet elapsed. Returns true if Ensembl is up,
358    * else false. Also retrieves and saves the current version of Ensembl data
359    * and REST services at intervals.
360    * 
361    * @return
362    */
363   protected boolean isEnsemblAvailable()
364   {
365     EnsemblInfo info = domainData.get(getDomain());
366
367     long now = System.currentTimeMillis();
368
369     /*
370      * check if we are waiting for 'Retry-After' to expire
371      */
372     if (info.retryAfter > now)
373     {
374       System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
375               + " secs to wait before retrying Ensembl");
376       return false;
377     }
378     else
379     {
380       info.retryAfter = 0;
381     }
382
383     /*
384      * recheck if Ensembl is up if it was down, or the recheck period has elapsed
385      */
386     boolean retestAvailability = (now
387             - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
388     if (!info.restAvailable || retestAvailability)
389     {
390       info.restAvailable = checkEnsembl();
391       info.lastAvailableCheckTime = now;
392     }
393
394     /*
395      * refetch Ensembl versions if the recheck period has elapsed
396      */
397     boolean refetchVersion = (now
398             - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
399     if (refetchVersion)
400     {
401       checkEnsemblRestVersion();
402       checkEnsemblDataVersion();
403       info.lastVersionCheckTime = now;
404     }
405
406     return info.restAvailable;
407   }
408
409   /**
410    * Constructs, writes and flushes the POST body of the request, containing the
411    * query ids in JSON format
412    * 
413    * @param connection
414    * @param ids
415    * @throws IOException
416    */
417   protected void writePostBody(HttpURLConnection connection,
418           List<String> ids) throws IOException
419   {
420     boolean first;
421     StringBuilder postBody = new StringBuilder(64);
422     postBody.append("{\"ids\":[");
423     first = true;
424     for (String id : ids)
425     {
426       if (!first)
427       {
428         postBody.append(",");
429       }
430       first = false;
431       postBody.append("\"");
432       postBody.append(id.trim());
433       postBody.append("\"");
434     }
435     postBody.append("]}");
436     byte[] thepostbody = postBody.toString().getBytes();
437     connection.setRequestProperty("Content-Length",
438             Integer.toString(thepostbody.length));
439     DataOutputStream wr = new DataOutputStream(
440             connection.getOutputStream());
441     wr.write(thepostbody);
442     wr.flush();
443     wr.close();
444   }
445
446   /**
447    * Fetches and checks Ensembl's REST version number
448    * 
449    * @return
450    */
451   private void checkEnsemblRestVersion()
452   {
453     EnsemblInfo info = domainData.get(getDomain());
454
455     JSONParser jp = new JSONParser();
456     URL url = null;
457     try
458     {
459       url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_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(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
526       BufferedReader br = getHttpResponse(url, null);
527       if (br != null)
528       {
529         JSONObject val = (JSONObject) jp.parse(br);
530         JSONArray versions = (JSONArray) val.get("releases");
531         domainData.get(getDomain()).dataVersion = versions.get(0)
532                 .toString();
533       }
534     } catch (Throwable t)
535     {
536       System.err.println(
537               "Error checking Ensembl data version: " + t.getMessage());
538     }
539   }
540
541   public String getEnsemblDataVersion()
542   {
543     return domainData.get(getDomain()).dataVersion;
544   }
545
546   @Override
547   public String getDbVersion()
548   {
549     return getEnsemblDataVersion();
550   }
551
552 }