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