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