2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.ext.ensembl;
23 import jalview.bin.Jalview;
24 import jalview.util.StringUtils;
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.ProtocolException;
35 import java.util.HashMap;
36 import java.util.List;
39 import javax.ws.rs.HttpMethod;
41 import org.json.simple.JSONArray;
42 import org.json.simple.JSONObject;
43 import org.json.simple.parser.JSONParser;
46 * Base class for Ensembl REST service clients
50 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
52 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
54 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
56 private static final int MAX_RETRIES = 3;
58 private static final int HTTP_OK = 200;
60 private static final int HTTP_OVERLOAD = 429;
63 * update these constants when Jalview has been checked / updated for
64 * changes to Ensembl REST API (ref JAL-2105)
65 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
66 * @see http://rest.ensembl.org/info/rest?content-type=application/json
68 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "7.0";
70 private static final String LATEST_ENSEMBL_REST_VERSION = "7.0";
72 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
74 private static Map<String, EnsemblData> domainData;
76 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
78 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
80 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
84 domainData = new HashMap<>();
85 domainData.put(DEFAULT_ENSEMBL_BASEURL,
86 new EnsemblData(DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
87 domainData.put(DEFAULT_ENSEMBL_GENOMES_BASEURL, new EnsemblData(
88 DEFAULT_ENSEMBL_GENOMES_BASEURL, LATEST_ENSEMBLGENOMES_REST_VERSION));
91 protected volatile boolean inProgress = false;
94 * Default constructor to use rest.ensembl.org
96 public EnsemblRestClient()
101 * initialise domain info lazily
103 if (!domainData.containsKey(ensemblDomain))
105 domainData.put(ensemblDomain,
106 new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
108 if (!domainData.containsKey(ensemblGenomesDomain))
110 domainData.put(ensemblGenomesDomain, new EnsemblData(
111 ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
116 * Constructor given the target domain to fetch data from
120 public EnsemblRestClient(String d)
126 public boolean queryInProgress()
132 public StringBuffer getRawRecords()
138 * Returns the URL for the client http request
142 * @throws MalformedURLException
144 protected abstract URL getUrl(List<String> ids)
145 throws MalformedURLException;
148 * Returns true if client uses GET method, false if it uses POST
152 protected abstract boolean useGetRequest();
155 * Returns the desired value for the Content-Type request header. Default is
156 * application/json, override if required to vary this.
159 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
161 protected String getRequestMimeType()
163 return "application/json";
167 * Return the desired value for the Accept request header. Default is
168 * application/json, override if required to vary this.
171 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
173 protected String getResponseMimeType()
175 return "application/json";
179 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
180 * indicates available, else false
182 * @see http://rest.ensembl.org/documentation/info/ping
185 boolean checkEnsembl()
187 BufferedReader br = null;
188 String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
191 // note this format works for both ensembl and ensemblgenomes
192 // info/ping.json works for ensembl only (March 2016)
193 URL ping = new URL(pingUrl);
196 * expect {"ping":1} if ok
197 * if ping takes more than 2 seconds to respond, treat as if unavailable
199 br = getHttpResponse(ping, null, 2 * 1000);
202 // error reponse status
205 JSONParser jp = new JSONParser();
206 JSONObject val = (JSONObject) jp.parse(br);
207 String pingString = val.get("ping").toString();
208 return pingString != null;
209 } catch (Throwable t)
212 "Error connecting to " + pingUrl + ": " + t.getMessage());
220 } catch (IOException e)
230 * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
231 * If the request failed the return value may be null.
235 * @throws IOException
237 protected BufferedReader getSequenceReader(List<String> ids)
240 URL url = getUrl(ids);
242 BufferedReader reader = getHttpResponse(url, ids);
247 * Gets a reader to the HTTP response, using the default read timeout of 5
253 * @throws IOException
255 protected BufferedReader getHttpResponse(URL url, List<String> ids)
258 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
262 * Sends the HTTP request and gets the response as a reader. Returns null if
263 * the HTTP response code was not 200.
267 * written as Json POST body if more than one
271 * @throws IOException
273 protected BufferedReader getHttpResponse(URL url, List<String> ids,
274 int readTimeout) throws IOException
276 int retriesLeft = MAX_RETRIES;
277 HttpURLConnection connection = null;
278 int responseCode = 0;
280 while (retriesLeft > 0)
282 connection = tryConnection(url, ids, readTimeout);
283 responseCode = connection.getResponseCode();
284 if (responseCode == HTTP_OVERLOAD) // 429
287 checkRetryAfter(connection);
294 if (responseCode != HTTP_OK) // 200
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
300 System.err.println("Response code " + responseCode + " for " + url);
304 InputStream response = connection.getInputStream();
306 // System.out.println(getClass().getName() + " took "
307 // + (System.currentTimeMillis() - now) + "ms to fetch");
309 BufferedReader reader = null;
310 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
319 * @throws IOException
320 * @throws ProtocolException
322 protected HttpURLConnection tryConnection(URL url, List<String> ids,
323 int readTimeout) throws IOException, ProtocolException
325 // System.out.println(System.currentTimeMillis() + " " + url);
326 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
329 * POST method allows multiple queries in one request; it is supported for
330 * sequence queries, but not for overlap
332 boolean multipleIds = ids != null && ids.size() > 1;
333 connection.setRequestMethod(
334 multipleIds ? HttpMethod.POST : HttpMethod.GET);
335 connection.setRequestProperty("Content-Type", getRequestMimeType());
336 connection.setRequestProperty("Accept", getResponseMimeType());
338 connection.setDoInput(true);
339 connection.setDoOutput(multipleIds);
343 connection.setUseCaches(false);
344 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
345 connection.setReadTimeout(readTimeout);
350 writePostBody(connection, ids);
356 * Inspects response headers for a 'retry-after' directive, and waits for the
357 * directed period (if less than 10 seconds)
359 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
362 void checkRetryAfter(HttpURLConnection connection)
364 String retryDelay = connection.getHeaderField("Retry-After");
369 if (retryDelay != null)
373 int retrySecs = Integer.valueOf(retryDelay);
374 if (retrySecs > 0 && retrySecs < 10)
377 .println("Ensembl REST service rate limit exceeded, waiting "
378 + retryDelay + " seconds before retrying");
379 Thread.sleep(1000 * retrySecs);
381 } catch (NumberFormatException | InterruptedException e)
383 System.err.println("Error handling Retry-After: " + e.getMessage());
389 * Rechecks if Ensembl is responding, unless the last check was successful and
390 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
391 * else false. Also retrieves and saves the current version of Ensembl data
392 * and REST services at intervals.
396 protected boolean isEnsemblAvailable()
398 EnsemblData info = domainData.get(getDomain());
400 long now = System.currentTimeMillis();
403 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
405 boolean retestAvailability = (now
406 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
407 if (!info.restAvailable || retestAvailability)
409 info.restAvailable = checkEnsembl();
410 info.lastAvailableCheckTime = now;
414 * refetch Ensembl versions if the recheck period has elapsed
416 boolean refetchVersion = (now
417 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
420 checkEnsemblRestVersion();
421 checkEnsemblDataVersion();
422 info.lastVersionCheckTime = now;
425 return info.restAvailable;
429 * Constructs, writes and flushes the POST body of the request, containing the
430 * query ids in JSON format
434 * @throws IOException
436 protected void writePostBody(HttpURLConnection connection,
437 List<String> ids) throws IOException
440 StringBuilder postBody = new StringBuilder(64);
441 postBody.append("{\"ids\":[");
443 for (String id : ids)
447 postBody.append(",");
450 postBody.append("\"");
451 postBody.append(id.trim());
452 postBody.append("\"");
454 postBody.append("]}");
455 byte[] thepostbody = postBody.toString().getBytes();
456 connection.setRequestProperty("Content-Length",
457 Integer.toString(thepostbody.length));
458 DataOutputStream wr = new DataOutputStream(
459 connection.getOutputStream());
460 wr.write(thepostbody);
466 * Fetches and checks Ensembl's REST version number
470 private void checkEnsemblRestVersion()
472 EnsemblData info = domainData.get(getDomain());
474 JSONParser jp = new JSONParser();
478 url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON);
479 BufferedReader br = getHttpResponse(url, null);
484 JSONObject val = (JSONObject) jp.parse(br);
485 String version = val.get("release").toString();
486 String majorVersion = version.substring(0, version.indexOf("."));
487 String expected = info.expectedRestVersion;
488 String expectedMajorVersion = expected.substring(0,
489 expected.indexOf("."));
490 info.restMajorVersionMismatch = false;
494 * if actual REST major version is ahead of what we expect,
495 * record this in case we want to warn the user
497 if (Float.valueOf(majorVersion) > Float
498 .valueOf(expectedMajorVersion))
500 info.restMajorVersionMismatch = true;
502 } catch (NumberFormatException e)
504 System.err.println("Error in REST version: " + e.toString());
508 * check if REST version is later than what Jalview has tested against,
509 * if so warn; we don't worry if it is earlier (this indicates Jalview has
510 * been tested in advance against the next pending REST version)
512 boolean laterVersion = StringUtils.compareVersions(version,
516 System.err.println(String.format(
517 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
518 getDbSource(), expected, version, REST_CHANGE_LOG));
520 info.restVersion = version;
521 } catch (Throwable t)
524 "Error checking Ensembl REST version: " + t.getMessage());
528 public boolean isRestMajorVersionMismatch()
530 return domainData.get(getDomain()).restMajorVersionMismatch;
534 * Fetches and checks Ensembl's data version number
538 private void checkEnsemblDataVersion()
540 JSONParser jp = new JSONParser();
542 BufferedReader br = null;
546 url = new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
547 br = getHttpResponse(url, null);
550 JSONObject val = (JSONObject) jp.parse(br);
551 JSONArray versions = (JSONArray) val.get("releases");
552 domainData.get(getDomain()).dataVersion = versions.get(0)
555 } catch (Throwable t)
558 "Error checking Ensembl data version: " + t.getMessage());
566 } catch (IOException e)
574 public String getEnsemblDataVersion()
576 return domainData.get(getDomain()).dataVersion;
580 public String getDbVersion()
582 return getEnsemblDataVersion();