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
38 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "4.4";
40 private static final String LATEST_ENSEMBL_REST_VERSION = "4.5";
42 private static Map<String, EnsemblInfo> domainData;
44 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
45 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
47 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
49 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
51 private static final Regex TRANSCRIPT_REGEX = new Regex(
52 "(ENS)([A-Z]{3}|)T[0-9]{11}$");
54 private static final Regex GENE_REGEX = new Regex(
55 "(ENS)([A-Z]{3}|)G[0-9]{11}$");
59 domainData = new HashMap<String, EnsemblInfo>();
60 domainData.put(ENSEMBL_REST, new EnsemblInfo(ENSEMBL_REST,
61 LATEST_ENSEMBL_REST_VERSION));
62 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
63 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
66 protected volatile boolean inProgress = false;
69 * Default constructor to use rest.ensembl.org
71 public EnsemblRestClient()
77 * Constructor given the target domain to fetch data from
81 public EnsemblRestClient(String d)
87 * Answers true if the query matches the regular expression pattern for an
88 * Ensembl transcript stable identifier
93 public boolean isTranscriptIdentifier(String query)
95 return query == null ? false : TRANSCRIPT_REGEX.search(query);
99 * Answers true if the query matches the regular expression pattern for an
100 * Ensembl gene stable identifier
105 public boolean isGeneIdentifier(String query)
107 return query == null ? false : GENE_REGEX.search(query);
111 public boolean queryInProgress()
117 public StringBuffer getRawRecords()
123 * Returns the URL for the client http request
127 * @throws MalformedURLException
129 protected abstract URL getUrl(List<String> ids)
130 throws MalformedURLException;
133 * Returns true if client uses GET method, false if it uses POST
137 protected abstract boolean useGetRequest();
140 * Return the desired value for the Content-Type request header
145 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
147 protected abstract String getRequestMimeType(boolean multipleIds);
150 * Return the desired value for the Accept request header
153 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
155 protected abstract String getResponseMimeType();
158 * Tries to connect to Ensembl's REST 'ping' endpoint, and returns true if
159 * successful, else false
163 private boolean checkEnsembl()
167 // note this format works for both ensembl and ensemblgenomes
168 // info/ping.json works for ensembl only (March 2016)
169 URL ping = new URL(getDomain()
170 + "/info/ping?content-type=application/json");
171 HttpURLConnection conn = (HttpURLConnection) ping.openConnection();
172 int rc = conn.getResponseCode();
174 if (rc >= 200 && rc < 300)
178 } catch (Throwable t)
180 System.err.println("Error connecting to " + PING_URL + ": "
187 * returns a reader to a Fasta response from the Ensembl sequence endpoint
191 * @throws IOException
193 protected FileParse getSequenceReader(List<String> ids)
196 URL url = getUrl(ids);
198 BufferedReader reader = getHttpResponse(url, ids);
199 FileParse fp = new FileParse(reader, url.toString(), "HTTP_POST");
204 * Writes the HTTP request and gets the response as a reader.
208 * written as Json POST body if more than one
210 * @throws IOException
211 * if response code was not 200, or other I/O error
213 protected BufferedReader getHttpResponse(URL url, List<String> ids)
216 // long now = System.currentTimeMillis();
217 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
220 * POST method allows multiple queries in one request; it is supported for
221 * sequence queries, but not for overlap
223 boolean multipleIds = ids != null && ids.size() > 1;
224 connection.setRequestMethod(multipleIds ? HttpMethod.POST
226 connection.setRequestProperty("Content-Type",
227 getRequestMimeType(multipleIds));
228 connection.setRequestProperty("Accept", getResponseMimeType());
230 connection.setUseCaches(false);
231 connection.setDoInput(true);
232 connection.setDoOutput(multipleIds);
236 writePostBody(connection, ids);
239 InputStream response = connection.getInputStream();
240 int responseCode = connection.getResponseCode();
242 if (responseCode != 200)
245 * note: a GET request for an invalid id returns an error code e.g. 415
246 * but POST request returns 200 and an empty Fasta response
248 throw new IOException(
249 "Response code was not 200. Detected response was "
252 // System.out.println(getClass().getName() + " took "
253 // + (System.currentTimeMillis() - now) + "ms to fetch");
255 checkRateLimits(connection);
257 BufferedReader reader = null;
258 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
263 * Inspect response headers for any sign of server overload and respect any
264 * 'retry-after' directive
266 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
269 void checkRateLimits(HttpURLConnection connection)
271 // number of requests allowed per time interval:
272 String limit = connection.getHeaderField("X-RateLimit-Limit");
273 // length of quota time interval in seconds:
274 // String period = connection.getHeaderField("X-RateLimit-Period");
275 // seconds remaining until usage quota is reset:
276 String reset = connection.getHeaderField("X-RateLimit-Reset");
277 // number of requests remaining from quota for current period:
278 String remaining = connection.getHeaderField("X-RateLimit-Remaining");
279 // number of seconds to wait before retrying (if remaining == 0)
280 String retryDelay = connection.getHeaderField("Retry-After");
285 EnsemblInfo info = domainData.get(getDomain());
286 if (retryDelay != null)
288 System.err.println("Ensembl REST service rate limit exceeded, wait "
289 + retryDelay + " seconds before retrying");
292 info.retryAfter = System.currentTimeMillis()
293 + (1000 * Integer.valueOf(retryDelay));
294 } catch (NumberFormatException e)
296 System.err.println("Unexpected value for Retry-After: "
304 // System.out.println(String.format(
305 // "%s Ensembl requests remaining of %s (reset in %ss)",
306 // remaining, limit, reset));
311 * Rechecks if Ensembl is responding, unless the last check was successful and
312 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
313 * else false. Also retrieves and saves the current version of Ensembl data
314 * and REST services at intervals.
318 protected boolean isEnsemblAvailable()
320 EnsemblInfo info = domainData.get(getDomain());
322 long now = System.currentTimeMillis();
325 * check if we are waiting for 'Retry-After' to expire
327 if (info.retryAfter > now)
329 System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
330 + " secs to wait before retrying Ensembl");
339 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
341 boolean retestAvailability = (now - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
342 if (!info.restAvailable || retestAvailability)
344 info.restAvailable = checkEnsembl();
345 info.lastAvailableCheckTime = now;
349 * refetch Ensembl versions if the recheck period has elapsed
351 boolean refetchVersion = (now - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
354 checkEnsemblRestVersion();
355 checkEnsemblDataVersion();
356 info.lastVersionCheckTime = now;
359 return info.restAvailable;
363 * Constructs, writes and flushes the POST body of the request, containing the
364 * query ids in JSON format
368 * @throws IOException
370 protected void writePostBody(HttpURLConnection connection,
371 List<String> ids) throws IOException
374 StringBuilder postBody = new StringBuilder(64);
375 postBody.append("{\"ids\":[");
377 for (String id : ids)
381 postBody.append(",");
384 postBody.append("\"");
385 postBody.append(id.trim());
386 postBody.append("\"");
388 postBody.append("]}");
389 byte[] thepostbody = postBody.toString().getBytes();
390 connection.setRequestProperty("Content-Length",
391 Integer.toString(thepostbody.length));
392 DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
393 wr.write(thepostbody);
399 * Fetches and checks Ensembl's REST version number
403 private void checkEnsemblRestVersion()
405 EnsemblInfo info = domainData.get(getDomain());
407 JSONParser jp = new JSONParser();
411 url = new URL(getDomain()
412 + "/info/rest?content-type=application/json");
413 BufferedReader br = getHttpResponse(url, null);
414 JSONObject val = (JSONObject) jp.parse(br);
415 String version = val.get("release").toString();
416 String majorVersion = version.substring(0, version.indexOf("."));
417 String expected = info.expectedRestVersion;
418 String expectedMajorVersion = expected.substring(0,
419 expected.indexOf("."));
420 info.restMajorVersionMismatch = false;
424 * if actual REST major version is ahead of what we expect,
425 * record this in case we want to warn the user
427 if (Float.valueOf(majorVersion) > Float
428 .valueOf(expectedMajorVersion))
430 info.restMajorVersionMismatch = true;
432 } catch (NumberFormatException e)
434 System.err.println("Error in REST version: " + e.toString());
438 * check if REST version is later than what Jalview has tested against,
439 * if so warn; we don't worry if it is earlier (this indicates Jalview has
440 * been tested in advance against the next pending REST version)
442 boolean laterVersion = StringUtils.compareVersions(version, expected) == 1;
445 System.err.println(String.format(
446 "Expected %s REST version %s but found %s", getDbSource(),
450 info.restVersion = version;
451 } catch (Throwable t)
453 System.err.println("Error checking Ensembl REST version: "
458 public boolean isRestMajorVersionMismatch()
460 return domainData.get(getDomain()).restMajorVersionMismatch;
464 * Fetches and checks Ensembl's data version number
468 private void checkEnsemblDataVersion()
470 JSONParser jp = new JSONParser();
474 url = new URL(getDomain()
475 + "/info/data?content-type=application/json");
476 BufferedReader br = getHttpResponse(url, null);
477 JSONObject val = (JSONObject) jp.parse(br);
478 JSONArray versions = (JSONArray) val.get("releases");
479 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
480 } catch (Throwable t)
482 System.err.println("Error checking Ensembl data version: "
487 public String getEnsemblDataVersion()
489 return domainData.get(getDomain()).dataVersion;
493 public String getDbVersion()
495 return getEnsemblDataVersion();