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.io.DataSourceType;
25 import jalview.io.FileParse;
26 import jalview.util.StringUtils;
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;
37 import java.util.HashMap;
38 import java.util.List;
41 import javax.ws.rs.HttpMethod;
43 import org.json.simple.JSONArray;
44 import org.json.simple.JSONObject;
45 import org.json.simple.parser.JSONParser;
48 * Base class for Ensembl REST service clients
52 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
54 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
56 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
58 private static final int MAX_RETRIES = 3;
60 private static final int HTTP_OK = 200;
62 private static final int HTTP_OVERLOAD = 429;
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
70 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "6.3";
72 private static final String LATEST_ENSEMBL_REST_VERSION = "6.3";
74 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
76 private static Map<String, EnsemblData> domainData;
78 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
80 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
82 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
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));
93 protected volatile boolean inProgress = false;
96 * Default constructor to use rest.ensembl.org
98 public EnsemblRestClient()
103 * initialise domain info lazily
105 if (!domainData.containsKey(ensemblDomain))
107 domainData.put(ensemblDomain,
108 new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
110 if (!domainData.containsKey(ensemblGenomesDomain))
112 domainData.put(ensemblGenomesDomain, new EnsemblData(
113 ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
118 * Constructor given the target domain to fetch data from
122 public EnsemblRestClient(String d)
128 public boolean queryInProgress()
134 public StringBuffer getRawRecords()
140 * Returns the URL for the client http request
144 * @throws MalformedURLException
146 protected abstract URL getUrl(List<String> ids)
147 throws MalformedURLException;
150 * Returns true if client uses GET method, false if it uses POST
154 protected abstract boolean useGetRequest();
157 * Return the desired value for the Content-Type request header
162 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
164 protected abstract String getRequestMimeType(boolean multipleIds);
167 * Return the desired value for the Accept request header
170 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
172 protected abstract String getResponseMimeType();
175 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
176 * indicates available, else false
178 * @see http://rest.ensembl.org/documentation/info/ping
181 boolean checkEnsembl()
183 BufferedReader br = null;
184 String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
187 // note this format works for both ensembl and ensemblgenomes
188 // info/ping.json works for ensembl only (March 2016)
189 URL ping = new URL(pingUrl);
192 * expect {"ping":1} if ok
193 * if ping takes more than 2 seconds to respond, treat as if unavailable
195 br = getHttpResponse(ping, null, 2 * 1000);
198 // error reponse status
201 JSONParser jp = new JSONParser();
202 JSONObject val = (JSONObject) jp.parse(br);
203 String pingString = val.get("ping").toString();
204 return pingString != null;
205 } catch (Throwable t)
208 "Error connecting to " + pingUrl + ": " + t.getMessage());
216 } catch (IOException e)
226 * returns a reader to a Fasta response from the Ensembl sequence endpoint
230 * @throws IOException
232 protected FileParse getSequenceReader(List<String> ids) throws IOException
234 URL url = getUrl(ids);
236 BufferedReader reader = getHttpResponse(url, ids);
242 FileParse fp = new FileParse(reader, url.toString(),
248 * Gets a reader to the HTTP response, using the default read timeout of 5
254 * @throws IOException
256 protected BufferedReader getHttpResponse(URL url, List<String> ids)
259 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
263 * Sends the HTTP request and gets the response as a reader. Returns null if
264 * the HTTP response code was not 200.
268 * written as Json POST body if more than one
272 * @throws IOException
274 protected BufferedReader getHttpResponse(URL url, List<String> ids,
275 int readTimeout) throws IOException
277 int retriesLeft = MAX_RETRIES;
278 HttpURLConnection connection = null;
279 int responseCode = 0;
281 while (retriesLeft > 0)
283 connection = tryConnection(url, ids, readTimeout);
284 responseCode = connection.getResponseCode();
285 if (responseCode == HTTP_OVERLOAD) // 429
288 checkRetryAfter(connection);
295 if (responseCode != HTTP_OK) // 200
298 * note: a GET request for an invalid id returns an error code e.g. 415
299 * but POST request returns 200 and an empty Fasta response
301 System.err.println("Response code " + responseCode + " for " + url);
305 InputStream response = connection.getInputStream();
307 // System.out.println(getClass().getName() + " took "
308 // + (System.currentTimeMillis() - now) + "ms to fetch");
310 BufferedReader reader = null;
311 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
320 * @throws IOException
321 * @throws ProtocolException
323 protected HttpURLConnection tryConnection(URL url, List<String> ids,
324 int readTimeout) throws IOException, ProtocolException
326 // System.out.println(System.currentTimeMillis() + " " + url);
327 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
330 * POST method allows multiple queries in one request; it is supported for
331 * sequence queries, but not for overlap
333 boolean multipleIds = ids != null && ids.size() > 1;
334 connection.setRequestMethod(
335 multipleIds ? HttpMethod.POST : HttpMethod.GET);
336 connection.setRequestProperty("Content-Type",
337 getRequestMimeType(multipleIds));
338 connection.setRequestProperty("Accept", getResponseMimeType());
340 connection.setDoInput(true);
341 connection.setDoOutput(multipleIds);
345 connection.setUseCaches(false);
346 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
347 connection.setReadTimeout(readTimeout);
352 writePostBody(connection, ids);
358 * Inspects response headers for a 'retry-after' directive, and waits for the
359 * directed period (if less than 10 seconds)
361 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
364 void checkRetryAfter(HttpURLConnection connection)
366 String retryDelay = connection.getHeaderField("Retry-After");
371 if (retryDelay != null)
375 int retrySecs = Integer.valueOf(retryDelay);
376 if (retrySecs > 0 && retrySecs < 10)
379 .println("Ensembl REST service rate limit exceeded, waiting "
380 + retryDelay + " seconds before retrying");
381 Thread.sleep(1000 * retrySecs);
383 } catch (NumberFormatException | InterruptedException e)
385 System.err.println("Error handling Retry-After: " + e.getMessage());
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.
398 protected boolean isEnsemblAvailable()
400 EnsemblData info = domainData.get(getDomain());
402 long now = System.currentTimeMillis();
405 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
407 boolean retestAvailability = (now
408 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
409 if (!info.restAvailable || retestAvailability)
411 info.restAvailable = checkEnsembl();
412 info.lastAvailableCheckTime = now;
416 * refetch Ensembl versions if the recheck period has elapsed
418 boolean refetchVersion = (now
419 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
422 checkEnsemblRestVersion();
423 checkEnsemblDataVersion();
424 info.lastVersionCheckTime = now;
427 return info.restAvailable;
431 * Constructs, writes and flushes the POST body of the request, containing the
432 * query ids in JSON format
436 * @throws IOException
438 protected void writePostBody(HttpURLConnection connection,
439 List<String> ids) throws IOException
442 StringBuilder postBody = new StringBuilder(64);
443 postBody.append("{\"ids\":[");
445 for (String id : ids)
449 postBody.append(",");
452 postBody.append("\"");
453 postBody.append(id.trim());
454 postBody.append("\"");
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);
468 * Fetches and checks Ensembl's REST version number
472 private void checkEnsemblRestVersion()
474 EnsemblData info = domainData.get(getDomain());
476 JSONParser jp = new JSONParser();
480 url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON);
481 BufferedReader br = getHttpResponse(url, null);
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;
496 * if actual REST major version is ahead of what we expect,
497 * record this in case we want to warn the user
499 if (Float.valueOf(majorVersion) > Float
500 .valueOf(expectedMajorVersion))
502 info.restMajorVersionMismatch = true;
504 } catch (NumberFormatException e)
506 System.err.println("Error in REST version: " + e.toString());
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)
514 boolean laterVersion = StringUtils.compareVersions(version,
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));
522 info.restVersion = version;
523 } catch (Throwable t)
526 "Error checking Ensembl REST version: " + t.getMessage());
530 public boolean isRestMajorVersionMismatch()
532 return domainData.get(getDomain()).restMajorVersionMismatch;
536 * Fetches and checks Ensembl's data version number
540 private void checkEnsemblDataVersion()
542 JSONParser jp = new JSONParser();
544 BufferedReader br = null;
548 url = new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
549 br = getHttpResponse(url, null);
552 JSONObject val = (JSONObject) jp.parse(br);
553 JSONArray versions = (JSONArray) val.get("releases");
554 domainData.get(getDomain()).dataVersion = versions.get(0)
557 } catch (Throwable t)
560 "Error checking Ensembl data version: " + t.getMessage());
568 } catch (IOException e)
576 public String getEnsemblDataVersion()
578 return domainData.get(getDomain()).dataVersion;
582 public String getDbVersion()
584 return getEnsemblDataVersion();