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.io.FileParse;
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;
34 import java.util.HashMap;
35 import java.util.List;
38 import javax.ws.rs.HttpMethod;
40 import org.json.simple.JSONArray;
41 import org.json.simple.JSONObject;
42 import org.json.simple.parser.JSONParser;
44 import com.stevesoft.pat.Regex;
47 * Base class for Ensembl REST service clients
51 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
53 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
55 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
58 * update these constants when Jalview has been checked / updated for
59 * changes to Ensembl REST API
60 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
61 * @see http://rest.ensembl.org/info/rest?content-type=application/json
63 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "4.6";
65 private static final String LATEST_ENSEMBL_REST_VERSION = "4.7";
67 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
69 private static Map<String, EnsemblInfo> domainData;
71 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
72 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
74 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
76 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
78 private static final Regex TRANSCRIPT_REGEX = new Regex(
79 "(ENS)([A-Z]{3}|)T[0-9]{11}$");
81 private static final Regex GENE_REGEX = new Regex(
82 "(ENS)([A-Z]{3}|)G[0-9]{11}$");
86 domainData = new HashMap<String, EnsemblInfo>();
87 domainData.put(ENSEMBL_REST, new EnsemblInfo(ENSEMBL_REST,
88 LATEST_ENSEMBL_REST_VERSION));
89 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
90 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
93 protected volatile boolean inProgress = false;
96 * Default constructor to use rest.ensembl.org
98 public EnsemblRestClient()
104 * Constructor given the target domain to fetch data from
108 public EnsemblRestClient(String d)
114 * Answers true if the query matches the regular expression pattern for an
115 * Ensembl transcript stable identifier
120 public boolean isTranscriptIdentifier(String query)
122 return query == null ? false : TRANSCRIPT_REGEX.search(query);
126 * Answers true if the query matches the regular expression pattern for an
127 * Ensembl gene stable identifier
132 public boolean isGeneIdentifier(String query)
134 return query == null ? false : GENE_REGEX.search(query);
138 public boolean queryInProgress()
144 public StringBuffer getRawRecords()
150 * Returns the URL for the client http request
154 * @throws MalformedURLException
156 protected abstract URL getUrl(List<String> ids)
157 throws MalformedURLException;
160 * Returns true if client uses GET method, false if it uses POST
164 protected abstract boolean useGetRequest();
167 * Return the desired value for the Content-Type request header
172 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
174 protected abstract String getRequestMimeType(boolean multipleIds);
177 * Return the desired value for the Accept request header
180 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
182 protected abstract String getResponseMimeType();
185 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
186 * indicates available, else false
188 * @see http://rest.ensembl.org/documentation/info/ping
191 private boolean checkEnsembl()
193 BufferedReader br = null;
196 // note this format works for both ensembl and ensemblgenomes
197 // info/ping.json works for ensembl only (March 2016)
198 URL ping = new URL(getDomain()
199 + "/info/ping?content-type=application/json");
202 * expect {"ping":1} if ok
203 * if ping takes more than 2 seconds to respond, treat as if unavailable
205 br = getHttpResponse(ping, null, 2 * 1000);
206 JSONParser jp = new JSONParser();
207 JSONObject val = (JSONObject) jp.parse(br);
208 String pingString = val.get("ping").toString();
209 return pingString != null;
210 } catch (Throwable t)
212 System.err.println("Error connecting to " + PING_URL + ": "
221 } catch (IOException e)
231 * returns a reader to a Fasta response from the Ensembl sequence endpoint
235 * @throws IOException
237 protected FileParse getSequenceReader(List<String> ids)
240 URL url = getUrl(ids);
242 BufferedReader reader = getHttpResponse(url, ids);
248 FileParse fp = new FileParse(reader, url.toString(), "HTTP_POST");
253 * Gets a reader to the HTTP response, using the default read timeout of 5
259 * @throws IOException
261 protected BufferedReader getHttpResponse(URL url, List<String> ids)
264 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
268 * Writes the HTTP request and gets the response as a reader.
272 * written as Json POST body if more than one
276 * @throws IOException
277 * if response code was not 200, or other I/O error
279 protected BufferedReader getHttpResponse(URL url, List<String> ids,
280 int readTimeout) throws IOException
282 // long now = System.currentTimeMillis();
283 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
286 * POST method allows multiple queries in one request; it is supported for
287 * sequence queries, but not for overlap
289 boolean multipleIds = ids != null && ids.size() > 1;
290 connection.setRequestMethod(multipleIds ? HttpMethod.POST
292 connection.setRequestProperty("Content-Type",
293 getRequestMimeType(multipleIds));
294 connection.setRequestProperty("Accept", getResponseMimeType());
296 connection.setUseCaches(false);
297 connection.setDoInput(true);
298 connection.setDoOutput(multipleIds);
300 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
301 connection.setReadTimeout(readTimeout);
305 writePostBody(connection, ids);
308 int responseCode = connection.getResponseCode();
310 if (responseCode != 200)
313 * note: a GET request for an invalid id returns an error code e.g. 415
314 * but POST request returns 200 and an empty Fasta response
316 System.err.println("Response code " + responseCode + " for " + url);
320 InputStream response = connection.getInputStream();
322 // System.out.println(getClass().getName() + " took "
323 // + (System.currentTimeMillis() - now) + "ms to fetch");
325 checkRateLimits(connection);
327 BufferedReader reader = null;
328 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
333 * Inspect response headers for any sign of server overload and respect any
334 * 'retry-after' directive
336 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
339 void checkRateLimits(HttpURLConnection connection)
341 // number of requests allowed per time interval:
342 String limit = connection.getHeaderField("X-RateLimit-Limit");
343 // length of quota time interval in seconds:
344 // String period = connection.getHeaderField("X-RateLimit-Period");
345 // seconds remaining until usage quota is reset:
346 String reset = connection.getHeaderField("X-RateLimit-Reset");
347 // number of requests remaining from quota for current period:
348 String remaining = connection.getHeaderField("X-RateLimit-Remaining");
349 // number of seconds to wait before retrying (if remaining == 0)
350 String retryDelay = connection.getHeaderField("Retry-After");
355 EnsemblInfo info = domainData.get(getDomain());
356 if (retryDelay != null)
358 System.err.println("Ensembl REST service rate limit exceeded, wait "
359 + retryDelay + " seconds before retrying");
362 info.retryAfter = System.currentTimeMillis()
363 + (1000 * Integer.valueOf(retryDelay));
364 } catch (NumberFormatException e)
366 System.err.println("Unexpected value for Retry-After: "
374 // System.out.println(String.format(
375 // "%s Ensembl requests remaining of %s (reset in %ss)",
376 // remaining, limit, reset));
381 * Rechecks if Ensembl is responding, unless the last check was successful and
382 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
383 * else false. Also retrieves and saves the current version of Ensembl data
384 * and REST services at intervals.
388 protected boolean isEnsemblAvailable()
390 EnsemblInfo info = domainData.get(getDomain());
392 long now = System.currentTimeMillis();
395 * check if we are waiting for 'Retry-After' to expire
397 if (info.retryAfter > now)
399 System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
400 + " secs to wait before retrying Ensembl");
409 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
411 boolean retestAvailability = (now - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
412 if (!info.restAvailable || retestAvailability)
414 info.restAvailable = checkEnsembl();
415 info.lastAvailableCheckTime = now;
419 * refetch Ensembl versions if the recheck period has elapsed
421 boolean refetchVersion = (now - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
424 checkEnsemblRestVersion();
425 checkEnsemblDataVersion();
426 info.lastVersionCheckTime = now;
429 return info.restAvailable;
433 * Constructs, writes and flushes the POST body of the request, containing the
434 * query ids in JSON format
438 * @throws IOException
440 protected void writePostBody(HttpURLConnection connection,
441 List<String> ids) throws IOException
444 StringBuilder postBody = new StringBuilder(64);
445 postBody.append("{\"ids\":[");
447 for (String id : ids)
451 postBody.append(",");
454 postBody.append("\"");
455 postBody.append(id.trim());
456 postBody.append("\"");
458 postBody.append("]}");
459 byte[] thepostbody = postBody.toString().getBytes();
460 connection.setRequestProperty("Content-Length",
461 Integer.toString(thepostbody.length));
462 DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
463 wr.write(thepostbody);
469 * Fetches and checks Ensembl's REST version number
473 private void checkEnsemblRestVersion()
475 EnsemblInfo info = domainData.get(getDomain());
477 JSONParser jp = new JSONParser();
481 url = new URL(getDomain()
482 + "/info/rest?content-type=application/json");
483 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, expected) == 1;
515 System.err.println(String.format(
516 "Expected %s REST version %s but found %s, see %s",
517 getDbSource(), expected, version, REST_CHANGE_LOG));
519 info.restVersion = version;
520 } catch (Throwable t)
522 System.err.println("Error checking Ensembl REST version: "
527 public boolean isRestMajorVersionMismatch()
529 return domainData.get(getDomain()).restMajorVersionMismatch;
533 * Fetches and checks Ensembl's data version number
537 private void checkEnsemblDataVersion()
539 JSONParser jp = new JSONParser();
543 url = new URL(getDomain()
544 + "/info/data?content-type=application/json");
545 BufferedReader br = getHttpResponse(url, null);
546 JSONObject val = (JSONObject) jp.parse(br);
547 JSONArray versions = (JSONArray) val.get("releases");
548 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
549 } catch (Throwable t)
551 System.err.println("Error checking Ensembl data version: "
556 public String getEnsemblDataVersion()
558 return domainData.get(getDomain()).dataVersion;
562 public String getDbVersion()
564 return getEnsemblDataVersion();