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