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.DataSourceType;
24 import jalview.io.FileParse;
25 import jalview.util.StringUtils;
27 import java.io.BufferedReader;
28 import java.io.DataOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.net.HttpURLConnection;
33 import java.net.MalformedURLException;
34 import java.net.ProtocolException;
36 import java.util.HashMap;
37 import java.util.List;
40 import javax.ws.rs.HttpMethod;
42 import org.json.simple.JSONArray;
43 import org.json.simple.JSONObject;
44 import org.json.simple.parser.JSONParser;
46 import com.stevesoft.pat.Regex;
49 * Base class for Ensembl REST service clients
53 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
55 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
57 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
60 * update these constants when Jalview has been checked / updated for
61 * changes to Ensembl REST API (ref JAL-2105)
62 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
63 * @see http://rest.ensembl.org/info/rest?content-type=application/json
65 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "5.0";
67 private static final String LATEST_ENSEMBL_REST_VERSION = "5.0";
69 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
71 private static Map<String, EnsemblInfo> domainData;
73 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
74 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
76 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
78 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
80 private static final Regex PROTEIN_REGEX = new Regex(
81 "(ENS)([A-Z]{3}|)P[0-9]{11}$");
83 private static final Regex TRANSCRIPT_REGEX = new Regex(
84 "(ENS)([A-Z]{3}|)T[0-9]{11}$");
86 private static final Regex GENE_REGEX = new Regex(
87 "(ENS)([A-Z]{3}|)G[0-9]{11}$");
91 domainData = new HashMap<String, EnsemblInfo>();
92 domainData.put(ENSEMBL_REST,
93 new EnsemblInfo(ENSEMBL_REST, LATEST_ENSEMBL_REST_VERSION));
94 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
95 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
98 protected volatile boolean inProgress = false;
101 * Default constructor to use rest.ensembl.org
103 public EnsemblRestClient()
109 * Constructor given the target domain to fetch data from
113 public EnsemblRestClient(String d)
119 * Answers true if the query matches the regular expression pattern for an
120 * Ensembl transcript stable identifier
125 public boolean isTranscriptIdentifier(String query)
127 return query == null ? false : TRANSCRIPT_REGEX.search(query);
131 * Answers true if the query matches the regular expression pattern for an
132 * Ensembl protein stable identifier
137 public boolean isProteinIdentifier(String query)
139 return query == null ? false : PROTEIN_REGEX.search(query);
143 * Answers true if the query matches the regular expression pattern for an
144 * Ensembl gene stable identifier
149 public boolean isGeneIdentifier(String query)
151 return query == null ? false : GENE_REGEX.search(query);
155 public boolean queryInProgress()
161 public StringBuffer getRawRecords()
167 * Returns the URL for the client http request
171 * @throws MalformedURLException
173 protected abstract URL getUrl(List<String> ids)
174 throws MalformedURLException;
177 * Returns true if client uses GET method, false if it uses POST
181 protected abstract boolean useGetRequest();
184 * Return the desired value for the Content-Type request header
189 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
191 protected abstract String getRequestMimeType(boolean multipleIds);
194 * Return the desired value for the Accept request header
197 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
199 protected abstract String getResponseMimeType();
202 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
203 * indicates available, else false
205 * @see http://rest.ensembl.org/documentation/info/ping
208 private boolean checkEnsembl()
210 BufferedReader br = null;
213 // note this format works for both ensembl and ensemblgenomes
214 // info/ping.json works for ensembl only (March 2016)
216 getDomain() + "/info/ping?content-type=application/json");
219 * expect {"ping":1} if ok
220 * if ping takes more than 2 seconds to respond, treat as if unavailable
222 br = getHttpResponse(ping, null, 2 * 1000);
223 JSONParser jp = new JSONParser();
224 JSONObject val = (JSONObject) jp.parse(br);
225 String pingString = val.get("ping").toString();
226 return pingString != null;
227 } catch (Throwable t)
230 "Error connecting to " + PING_URL + ": " + t.getMessage());
238 } catch (IOException e)
248 * returns a reader to a Fasta response from the Ensembl sequence endpoint
252 * @throws IOException
254 protected FileParse getSequenceReader(List<String> ids) throws IOException
256 URL url = getUrl(ids);
258 BufferedReader reader = getHttpResponse(url, ids);
264 FileParse fp = new FileParse(reader, url.toString(),
270 * Gets a reader to the HTTP response, using the default read timeout of 5
276 * @throws IOException
278 protected BufferedReader getHttpResponse(URL url, List<String> ids)
281 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
285 * Writes the HTTP request and gets the response as a reader.
289 * written as Json POST body if more than one
293 * @throws IOException
294 * if response code was not 200, or other I/O error
296 protected BufferedReader getHttpResponse(URL url, List<String> ids,
297 int readTimeout) throws IOException
299 // long now = System.currentTimeMillis();
301 int retriesLeft = maxRetries;
302 HttpURLConnection connection = null;
303 while (retriesLeft > 0)
305 connection = tryConnection(url, ids, readTimeout);
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"));
337 * @throws IOException
338 * @throws ProtocolException
340 protected HttpURLConnection tryConnection(URL url, List<String> ids,
341 int readTimeout) throws IOException, ProtocolException
343 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
346 * POST method allows multiple queries in one request; it is supported for
347 * sequence queries, but not for overlap
349 boolean multipleIds = ids != null && ids.size() > 1;
350 connection.setRequestMethod(
351 multipleIds ? HttpMethod.POST : HttpMethod.GET);
352 connection.setRequestProperty("Content-Type",
353 getRequestMimeType(multipleIds));
354 connection.setRequestProperty("Accept", getResponseMimeType());
356 connection.setUseCaches(false);
357 connection.setDoInput(true);
358 connection.setDoOutput(multipleIds);
360 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
361 connection.setReadTimeout(readTimeout);
365 writePostBody(connection, ids);
371 * Inspect response headers for any sign of server overload and respect any
372 * 'retry-after' directive
374 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
377 void checkRateLimits(HttpURLConnection connection)
379 // number of requests allowed per time interval:
380 String limit = connection.getHeaderField("X-RateLimit-Limit");
381 // length of quota time interval in seconds:
382 // String period = connection.getHeaderField("X-RateLimit-Period");
383 // seconds remaining until usage quota is reset:
384 String reset = connection.getHeaderField("X-RateLimit-Reset");
385 // number of requests remaining from quota for current period:
386 String remaining = connection.getHeaderField("X-RateLimit-Remaining");
387 // number of seconds to wait before retrying (if remaining == 0)
388 String retryDelay = connection.getHeaderField("Retry-After");
393 EnsemblInfo info = domainData.get(getDomain());
394 if (retryDelay != null)
396 System.err.println("Ensembl REST service rate limit exceeded, wait "
397 + retryDelay + " seconds before retrying");
400 info.retryAfter = System.currentTimeMillis()
401 + (1000 * Integer.valueOf(retryDelay));
402 } catch (NumberFormatException e)
405 .println("Unexpected value for Retry-After: " + retryDelay);
412 // System.out.println(String.format(
413 // "%s Ensembl requests remaining of %s (reset in %ss)",
414 // remaining, limit, reset));
419 * Rechecks if Ensembl is responding, unless the last check was successful and
420 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
421 * else false. Also retrieves and saves the current version of Ensembl data
422 * and REST services at intervals.
426 protected boolean isEnsemblAvailable()
428 EnsemblInfo info = domainData.get(getDomain());
430 long now = System.currentTimeMillis();
433 * check if we are waiting for 'Retry-After' to expire
435 if (info.retryAfter > now)
437 System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
438 + " secs to wait before retrying Ensembl");
447 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
449 boolean retestAvailability = (now
450 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
451 if (!info.restAvailable || retestAvailability)
453 info.restAvailable = checkEnsembl();
454 info.lastAvailableCheckTime = now;
458 * refetch Ensembl versions if the recheck period has elapsed
460 boolean refetchVersion = (now
461 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
464 checkEnsemblRestVersion();
465 checkEnsemblDataVersion();
466 info.lastVersionCheckTime = now;
469 return info.restAvailable;
473 * Constructs, writes and flushes the POST body of the request, containing the
474 * query ids in JSON format
478 * @throws IOException
480 protected void writePostBody(HttpURLConnection connection,
481 List<String> ids) throws IOException
484 StringBuilder postBody = new StringBuilder(64);
485 postBody.append("{\"ids\":[");
487 for (String id : ids)
491 postBody.append(",");
494 postBody.append("\"");
495 postBody.append(id.trim());
496 postBody.append("\"");
498 postBody.append("]}");
499 byte[] thepostbody = postBody.toString().getBytes();
500 connection.setRequestProperty("Content-Length",
501 Integer.toString(thepostbody.length));
502 DataOutputStream wr = new DataOutputStream(
503 connection.getOutputStream());
504 wr.write(thepostbody);
510 * Fetches and checks Ensembl's REST version number
514 private void checkEnsemblRestVersion()
516 EnsemblInfo info = domainData.get(getDomain());
518 JSONParser jp = new JSONParser();
523 getDomain() + "/info/rest?content-type=application/json");
524 BufferedReader br = getHttpResponse(url, null);
525 JSONObject val = (JSONObject) jp.parse(br);
526 String version = val.get("release").toString();
527 String majorVersion = version.substring(0, version.indexOf("."));
528 String expected = info.expectedRestVersion;
529 String expectedMajorVersion = expected.substring(0,
530 expected.indexOf("."));
531 info.restMajorVersionMismatch = false;
535 * if actual REST major version is ahead of what we expect,
536 * record this in case we want to warn the user
538 if (Float.valueOf(majorVersion) > Float
539 .valueOf(expectedMajorVersion))
541 info.restMajorVersionMismatch = true;
543 } catch (NumberFormatException e)
545 System.err.println("Error in REST version: " + e.toString());
549 * check if REST version is later than what Jalview has tested against,
550 * if so warn; we don't worry if it is earlier (this indicates Jalview has
551 * been tested in advance against the next pending REST version)
553 boolean laterVersion = StringUtils.compareVersions(version,
557 System.err.println(String.format(
558 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
559 getDbSource(), expected, version, REST_CHANGE_LOG));
561 info.restVersion = version;
562 } catch (Throwable t)
565 "Error checking Ensembl REST version: " + t.getMessage());
569 public boolean isRestMajorVersionMismatch()
571 return domainData.get(getDomain()).restMajorVersionMismatch;
575 * Fetches and checks Ensembl's data version number
579 private void checkEnsemblDataVersion()
581 JSONParser jp = new JSONParser();
586 getDomain() + "/info/data?content-type=application/json");
587 BufferedReader br = getHttpResponse(url, null);
588 JSONObject val = (JSONObject) jp.parse(br);
589 JSONArray versions = (JSONArray) val.get("releases");
590 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
591 } catch (Throwable t)
594 "Error checking Ensembl data version: " + t.getMessage());
598 public String getEnsemblDataVersion()
600 return domainData.get(getDomain()).dataVersion;
604 public String getDbVersion()
606 return getEnsemblDataVersion();