1 package jalview.ext.ensembl;
3 import jalview.io.FileParse;
4 import jalview.util.StringUtils;
6 import java.io.BufferedReader;
7 import java.io.DataOutputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
11 import java.net.HttpURLConnection;
12 import java.net.MalformedURLException;
14 import java.util.HashMap;
15 import java.util.List;
18 import javax.ws.rs.HttpMethod;
20 import org.json.simple.JSONArray;
21 import org.json.simple.JSONObject;
22 import org.json.simple.parser.JSONParser;
24 import com.stevesoft.pat.Regex;
27 * Base class for Ensembl REST service clients
31 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
34 * update these constants when Jalview has been checked / updated for
35 * changes to Ensembl REST API
36 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
37 * @see http://rest.ensembl.org/info/rest?content-type=application/json
39 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "4.6";
41 private static final String LATEST_ENSEMBL_REST_VERSION = "4.7";
43 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
45 private static Map<String, EnsemblInfo> domainData;
47 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
48 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
50 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
52 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
54 private static final Regex TRANSCRIPT_REGEX = new Regex(
55 "(ENS)([A-Z]{3}|)T[0-9]{11}$");
57 private static final Regex GENE_REGEX = new Regex(
58 "(ENS)([A-Z]{3}|)G[0-9]{11}$");
62 domainData = new HashMap<String, EnsemblInfo>();
63 domainData.put(ENSEMBL_REST, new EnsemblInfo(ENSEMBL_REST,
64 LATEST_ENSEMBL_REST_VERSION));
65 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
66 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
69 protected volatile boolean inProgress = false;
72 * Default constructor to use rest.ensembl.org
74 public EnsemblRestClient()
80 * Constructor given the target domain to fetch data from
84 public EnsemblRestClient(String d)
90 * Answers true if the query matches the regular expression pattern for an
91 * Ensembl transcript stable identifier
96 public boolean isTranscriptIdentifier(String query)
98 return query == null ? false : TRANSCRIPT_REGEX.search(query);
102 * Answers true if the query matches the regular expression pattern for an
103 * Ensembl gene stable identifier
108 public boolean isGeneIdentifier(String query)
110 return query == null ? false : GENE_REGEX.search(query);
114 public boolean queryInProgress()
120 public StringBuffer getRawRecords()
126 * Returns the URL for the client http request
130 * @throws MalformedURLException
132 protected abstract URL getUrl(List<String> ids)
133 throws MalformedURLException;
136 * Returns true if client uses GET method, false if it uses POST
140 protected abstract boolean useGetRequest();
143 * Return the desired value for the Content-Type request header
148 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
150 protected abstract String getRequestMimeType(boolean multipleIds);
153 * Return the desired value for the Accept request header
156 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
158 protected abstract String getResponseMimeType();
161 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
162 * indicates available, else false
164 * @see http://rest.ensembl.org/documentation/info/ping
167 private boolean checkEnsembl()
169 HttpURLConnection conn = null;
172 // note this format works for both ensembl and ensemblgenomes
173 // info/ping.json works for ensembl only (March 2016)
174 URL ping = new URL(getDomain()
175 + "/info/ping?content-type=application/json");
178 * expect {"ping":1} if ok
180 BufferedReader br = getHttpResponse(ping, null);
181 JSONParser jp = new JSONParser();
182 JSONObject val = (JSONObject) jp.parse(br);
183 String pingString = val.get("ping").toString();
184 return pingString != null;
185 } catch (Throwable t)
187 System.err.println("Error connecting to " + PING_URL + ": "
200 * returns a reader to a Fasta response from the Ensembl sequence endpoint
204 * @throws IOException
206 protected FileParse getSequenceReader(List<String> ids)
209 URL url = getUrl(ids);
211 BufferedReader reader = getHttpResponse(url, ids);
217 FileParse fp = new FileParse(reader, url.toString(), "HTTP_POST");
222 * Writes the HTTP request and gets the response as a reader.
226 * written as Json POST body if more than one
228 * @throws IOException
229 * if response code was not 200, or other I/O error
231 protected BufferedReader getHttpResponse(URL url, List<String> ids)
234 // long now = System.currentTimeMillis();
235 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
238 * POST method allows multiple queries in one request; it is supported for
239 * sequence queries, but not for overlap
241 boolean multipleIds = ids != null && ids.size() > 1;
242 connection.setRequestMethod(multipleIds ? HttpMethod.POST
244 connection.setRequestProperty("Content-Type",
245 getRequestMimeType(multipleIds));
246 connection.setRequestProperty("Accept", getResponseMimeType());
248 connection.setUseCaches(false);
249 connection.setDoInput(true);
250 connection.setDoOutput(multipleIds);
254 writePostBody(connection, ids);
257 int responseCode = connection.getResponseCode();
259 if (responseCode != 200)
262 * note: a GET request for an invalid id returns an error code e.g. 415
263 * but POST request returns 200 and an empty Fasta response
265 System.err.println("Response code " + responseCode + " for " + url);
269 InputStream response = connection.getInputStream();
271 // System.out.println(getClass().getName() + " took "
272 // + (System.currentTimeMillis() - now) + "ms to fetch");
274 checkRateLimits(connection);
276 BufferedReader reader = null;
277 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
282 * Inspect response headers for any sign of server overload and respect any
283 * 'retry-after' directive
285 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
288 void checkRateLimits(HttpURLConnection connection)
290 // number of requests allowed per time interval:
291 String limit = connection.getHeaderField("X-RateLimit-Limit");
292 // length of quota time interval in seconds:
293 // String period = connection.getHeaderField("X-RateLimit-Period");
294 // seconds remaining until usage quota is reset:
295 String reset = connection.getHeaderField("X-RateLimit-Reset");
296 // number of requests remaining from quota for current period:
297 String remaining = connection.getHeaderField("X-RateLimit-Remaining");
298 // number of seconds to wait before retrying (if remaining == 0)
299 String retryDelay = connection.getHeaderField("Retry-After");
304 EnsemblInfo info = domainData.get(getDomain());
305 if (retryDelay != null)
307 System.err.println("Ensembl REST service rate limit exceeded, wait "
308 + retryDelay + " seconds before retrying");
311 info.retryAfter = System.currentTimeMillis()
312 + (1000 * Integer.valueOf(retryDelay));
313 } catch (NumberFormatException e)
315 System.err.println("Unexpected value for Retry-After: "
323 // System.out.println(String.format(
324 // "%s Ensembl requests remaining of %s (reset in %ss)",
325 // remaining, limit, reset));
330 * Rechecks if Ensembl is responding, unless the last check was successful and
331 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
332 * else false. Also retrieves and saves the current version of Ensembl data
333 * and REST services at intervals.
337 protected boolean isEnsemblAvailable()
339 EnsemblInfo info = domainData.get(getDomain());
341 long now = System.currentTimeMillis();
344 * check if we are waiting for 'Retry-After' to expire
346 if (info.retryAfter > now)
348 System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
349 + " secs to wait before retrying Ensembl");
358 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
360 boolean retestAvailability = (now - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
361 if (!info.restAvailable || retestAvailability)
363 info.restAvailable = checkEnsembl();
364 info.lastAvailableCheckTime = now;
368 * refetch Ensembl versions if the recheck period has elapsed
370 boolean refetchVersion = (now - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
373 checkEnsemblRestVersion();
374 checkEnsemblDataVersion();
375 info.lastVersionCheckTime = now;
378 return info.restAvailable;
382 * Constructs, writes and flushes the POST body of the request, containing the
383 * query ids in JSON format
387 * @throws IOException
389 protected void writePostBody(HttpURLConnection connection,
390 List<String> ids) throws IOException
393 StringBuilder postBody = new StringBuilder(64);
394 postBody.append("{\"ids\":[");
396 for (String id : ids)
400 postBody.append(",");
403 postBody.append("\"");
404 postBody.append(id.trim());
405 postBody.append("\"");
407 postBody.append("]}");
408 byte[] thepostbody = postBody.toString().getBytes();
409 connection.setRequestProperty("Content-Length",
410 Integer.toString(thepostbody.length));
411 DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
412 wr.write(thepostbody);
418 * Fetches and checks Ensembl's REST version number
422 private void checkEnsemblRestVersion()
424 EnsemblInfo info = domainData.get(getDomain());
426 JSONParser jp = new JSONParser();
430 url = new URL(getDomain()
431 + "/info/rest?content-type=application/json");
432 BufferedReader br = getHttpResponse(url, null);
433 JSONObject val = (JSONObject) jp.parse(br);
434 String version = val.get("release").toString();
435 String majorVersion = version.substring(0, version.indexOf("."));
436 String expected = info.expectedRestVersion;
437 String expectedMajorVersion = expected.substring(0,
438 expected.indexOf("."));
439 info.restMajorVersionMismatch = false;
443 * if actual REST major version is ahead of what we expect,
444 * record this in case we want to warn the user
446 if (Float.valueOf(majorVersion) > Float
447 .valueOf(expectedMajorVersion))
449 info.restMajorVersionMismatch = true;
451 } catch (NumberFormatException e)
453 System.err.println("Error in REST version: " + e.toString());
457 * check if REST version is later than what Jalview has tested against,
458 * if so warn; we don't worry if it is earlier (this indicates Jalview has
459 * been tested in advance against the next pending REST version)
461 boolean laterVersion = StringUtils.compareVersions(version, expected) == 1;
464 System.err.println(String.format(
465 "Expected %s REST version %s but found %s, see %s",
466 getDbSource(), expected, version, REST_CHANGE_LOG));
468 info.restVersion = version;
469 } catch (Throwable t)
471 System.err.println("Error checking Ensembl REST version: "
476 public boolean isRestMajorVersionMismatch()
478 return domainData.get(getDomain()).restMajorVersionMismatch;
482 * Fetches and checks Ensembl's data version number
486 private void checkEnsemblDataVersion()
488 JSONParser jp = new JSONParser();
492 url = new URL(getDomain()
493 + "/info/data?content-type=application/json");
494 BufferedReader br = getHttpResponse(url, null);
495 JSONObject val = (JSONObject) jp.parse(br);
496 JSONArray versions = (JSONArray) val.get("releases");
497 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
498 } catch (Throwable t)
500 System.err.println("Error checking Ensembl data version: "
505 public String getEnsemblDataVersion()
507 return domainData.get(getDomain()).dataVersion;
511 public String getDbVersion()
513 return getEnsemblDataVersion();