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