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