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