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.6";
40 private static final String LATEST_ENSEMBL_REST_VERSION = "4.6";
42 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
44 private static Map<String, EnsemblInfo> domainData;
46 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
47 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
49 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
51 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
53 private static final Regex TRANSCRIPT_REGEX = new Regex(
54 "(ENS)([A-Z]{3}|)T[0-9]{11}$");
56 private static final Regex GENE_REGEX = new Regex(
57 "(ENS)([A-Z]{3}|)G[0-9]{11}$");
61 domainData = new HashMap<String, EnsemblInfo>();
62 domainData.put(ENSEMBL_REST, new EnsemblInfo(ENSEMBL_REST,
63 LATEST_ENSEMBL_REST_VERSION));
64 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
65 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
68 protected volatile boolean inProgress = false;
71 * Default constructor to use rest.ensembl.org
73 public EnsemblRestClient()
79 * Constructor given the target domain to fetch data from
83 public EnsemblRestClient(String d)
89 * Answers true if the query matches the regular expression pattern for an
90 * Ensembl transcript stable identifier
95 public boolean isTranscriptIdentifier(String query)
97 return query == null ? false : TRANSCRIPT_REGEX.search(query);
101 * Answers true if the query matches the regular expression pattern for an
102 * Ensembl gene stable identifier
107 public boolean isGeneIdentifier(String query)
109 return query == null ? false : GENE_REGEX.search(query);
113 public boolean queryInProgress()
119 public StringBuffer getRawRecords()
125 * Returns the URL for the client http request
129 * @throws MalformedURLException
131 protected abstract URL getUrl(List<String> ids)
132 throws MalformedURLException;
135 * Returns true if client uses GET method, false if it uses POST
139 protected abstract boolean useGetRequest();
142 * Return the desired value for the Content-Type request header
147 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
149 protected abstract String getRequestMimeType(boolean multipleIds);
152 * Return the desired value for the Accept request header
155 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
157 protected abstract String getResponseMimeType();
160 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
161 * indicates available, else false
163 * @see http://rest.ensembl.org/documentation/info/ping
166 private boolean checkEnsembl()
168 HttpURLConnection conn = null;
171 // note this format works for both ensembl and ensemblgenomes
172 // info/ping.json works for ensembl only (March 2016)
173 URL ping = new URL(getDomain()
174 + "/info/ping?content-type=application/json");
177 * expect {"ping":1} if ok
179 BufferedReader br = getHttpResponse(ping, null);
180 JSONParser jp = new JSONParser();
181 JSONObject val = (JSONObject) jp.parse(br);
182 String pingString = val.get("ping").toString();
183 return pingString != null;
184 } catch (Throwable t)
186 System.err.println("Error connecting to " + PING_URL + ": "
199 * returns a reader to a Fasta response from the Ensembl sequence endpoint
203 * @throws IOException
205 protected FileParse getSequenceReader(List<String> ids)
208 URL url = getUrl(ids);
210 BufferedReader reader = getHttpResponse(url, ids);
211 FileParse fp = new FileParse(reader, url.toString(), "HTTP_POST");
216 * Writes the HTTP request and gets the response as a reader.
220 * written as Json POST body if more than one
222 * @throws IOException
223 * if response code was not 200, or other I/O error
225 protected BufferedReader getHttpResponse(URL url, List<String> ids)
228 // long now = System.currentTimeMillis();
229 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
232 * POST method allows multiple queries in one request; it is supported for
233 * sequence queries, but not for overlap
235 boolean multipleIds = ids != null && ids.size() > 1;
236 connection.setRequestMethod(multipleIds ? HttpMethod.POST
238 connection.setRequestProperty("Content-Type",
239 getRequestMimeType(multipleIds));
240 connection.setRequestProperty("Accept", getResponseMimeType());
242 connection.setUseCaches(false);
243 connection.setDoInput(true);
244 connection.setDoOutput(multipleIds);
248 writePostBody(connection, ids);
251 InputStream response = connection.getInputStream();
252 int responseCode = connection.getResponseCode();
254 if (responseCode != 200)
257 * note: a GET request for an invalid id returns an error code e.g. 415
258 * but POST request returns 200 and an empty Fasta response
260 throw new IOException(
261 "Response code was not 200. Detected response was "
264 // System.out.println(getClass().getName() + " took "
265 // + (System.currentTimeMillis() - now) + "ms to fetch");
267 checkRateLimits(connection);
269 BufferedReader reader = null;
270 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
275 * Inspect response headers for any sign of server overload and respect any
276 * 'retry-after' directive
278 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
281 void checkRateLimits(HttpURLConnection connection)
283 // number of requests allowed per time interval:
284 String limit = connection.getHeaderField("X-RateLimit-Limit");
285 // length of quota time interval in seconds:
286 // String period = connection.getHeaderField("X-RateLimit-Period");
287 // seconds remaining until usage quota is reset:
288 String reset = connection.getHeaderField("X-RateLimit-Reset");
289 // number of requests remaining from quota for current period:
290 String remaining = connection.getHeaderField("X-RateLimit-Remaining");
291 // number of seconds to wait before retrying (if remaining == 0)
292 String retryDelay = connection.getHeaderField("Retry-After");
297 EnsemblInfo info = domainData.get(getDomain());
298 if (retryDelay != null)
300 System.err.println("Ensembl REST service rate limit exceeded, wait "
301 + retryDelay + " seconds before retrying");
304 info.retryAfter = System.currentTimeMillis()
305 + (1000 * Integer.valueOf(retryDelay));
306 } catch (NumberFormatException e)
308 System.err.println("Unexpected value for Retry-After: "
316 // System.out.println(String.format(
317 // "%s Ensembl requests remaining of %s (reset in %ss)",
318 // remaining, limit, reset));
323 * Rechecks if Ensembl is responding, unless the last check was successful and
324 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
325 * else false. Also retrieves and saves the current version of Ensembl data
326 * and REST services at intervals.
330 protected boolean isEnsemblAvailable()
332 EnsemblInfo info = domainData.get(getDomain());
334 long now = System.currentTimeMillis();
337 * check if we are waiting for 'Retry-After' to expire
339 if (info.retryAfter > now)
341 System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
342 + " secs to wait before retrying Ensembl");
351 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
353 boolean retestAvailability = (now - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
354 if (!info.restAvailable || retestAvailability)
356 info.restAvailable = checkEnsembl();
357 info.lastAvailableCheckTime = now;
361 * refetch Ensembl versions if the recheck period has elapsed
363 boolean refetchVersion = (now - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
366 checkEnsemblRestVersion();
367 checkEnsemblDataVersion();
368 info.lastVersionCheckTime = now;
371 return info.restAvailable;
375 * Constructs, writes and flushes the POST body of the request, containing the
376 * query ids in JSON format
380 * @throws IOException
382 protected void writePostBody(HttpURLConnection connection,
383 List<String> ids) throws IOException
386 StringBuilder postBody = new StringBuilder(64);
387 postBody.append("{\"ids\":[");
389 for (String id : ids)
393 postBody.append(",");
396 postBody.append("\"");
397 postBody.append(id.trim());
398 postBody.append("\"");
400 postBody.append("]}");
401 byte[] thepostbody = postBody.toString().getBytes();
402 connection.setRequestProperty("Content-Length",
403 Integer.toString(thepostbody.length));
404 DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
405 wr.write(thepostbody);
411 * Fetches and checks Ensembl's REST version number
415 private void checkEnsemblRestVersion()
417 EnsemblInfo info = domainData.get(getDomain());
419 JSONParser jp = new JSONParser();
423 url = new URL(getDomain()
424 + "/info/rest?content-type=application/json");
425 BufferedReader br = getHttpResponse(url, null);
426 JSONObject val = (JSONObject) jp.parse(br);
427 String version = val.get("release").toString();
428 String majorVersion = version.substring(0, version.indexOf("."));
429 String expected = info.expectedRestVersion;
430 String expectedMajorVersion = expected.substring(0,
431 expected.indexOf("."));
432 info.restMajorVersionMismatch = false;
436 * if actual REST major version is ahead of what we expect,
437 * record this in case we want to warn the user
439 if (Float.valueOf(majorVersion) > Float
440 .valueOf(expectedMajorVersion))
442 info.restMajorVersionMismatch = true;
444 } catch (NumberFormatException e)
446 System.err.println("Error in REST version: " + e.toString());
450 * check if REST version is later than what Jalview has tested against,
451 * if so warn; we don't worry if it is earlier (this indicates Jalview has
452 * been tested in advance against the next pending REST version)
454 boolean laterVersion = StringUtils.compareVersions(version, expected) == 1;
457 System.err.println(String.format(
458 "Expected %s REST version %s but found %s, see %s",
459 getDbSource(), expected, version, REST_CHANGE_LOG));
461 info.restVersion = version;
462 } catch (Throwable t)
464 System.err.println("Error checking Ensembl REST version: "
469 public boolean isRestMajorVersionMismatch()
471 return domainData.get(getDomain()).restMajorVersionMismatch;
475 * Fetches and checks Ensembl's data version number
479 private void checkEnsemblDataVersion()
481 JSONParser jp = new JSONParser();
485 url = new URL(getDomain()
486 + "/info/data?content-type=application/json");
487 BufferedReader br = getHttpResponse(url, null);
488 JSONObject val = (JSONObject) jp.parse(br);
489 JSONArray versions = (JSONArray) val.get("releases");
490 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
491 } catch (Throwable t)
493 System.err.println("Error checking Ensembl data version: "
498 public String getEnsemblDataVersion()
500 return domainData.get(getDomain()).dataVersion;
504 public String getDbVersion()
506 return getEnsemblDataVersion();