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