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