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