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