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;
35 import java.util.HashMap;
36 import java.util.List;
39 import javax.ws.rs.HttpMethod;
41 import org.json.simple.JSONArray;
42 import org.json.simple.JSONObject;
43 import org.json.simple.parser.JSONParser;
45 import com.stevesoft.pat.Regex;
48 * Base class for Ensembl REST service clients
52 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
54 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
56 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
59 * update these constants when Jalview has been checked / updated for
60 * changes to Ensembl REST API (ref JAL-2105)
61 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
62 * @see http://rest.ensembl.org/info/rest?content-type=application/json
64 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "5.0";
66 private static final String LATEST_ENSEMBL_REST_VERSION = "5.0";
68 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
70 private static Map<String, EnsemblInfo> domainData;
72 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
73 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
75 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
77 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
79 private static final Regex PROTEIN_REGEX = new Regex(
80 "(ENS)([A-Z]{3}|)P[0-9]{11}$");
82 private static final Regex TRANSCRIPT_REGEX = new Regex(
83 "(ENS)([A-Z]{3}|)T[0-9]{11}$");
85 private static final Regex GENE_REGEX = new Regex(
86 "(ENS)([A-Z]{3}|)G[0-9]{11}$");
90 domainData = new HashMap<String, EnsemblInfo>();
91 domainData.put(ENSEMBL_REST, new EnsemblInfo(ENSEMBL_REST,
92 LATEST_ENSEMBL_REST_VERSION));
93 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
94 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
97 protected volatile boolean inProgress = false;
100 * Default constructor to use rest.ensembl.org
102 public EnsemblRestClient()
108 * Constructor given the target domain to fetch data from
112 public EnsemblRestClient(String d)
118 * Answers true if the query matches the regular expression pattern for an
119 * Ensembl transcript stable identifier
124 public boolean isTranscriptIdentifier(String query)
126 return query == null ? false : TRANSCRIPT_REGEX.search(query);
130 * Answers true if the query matches the regular expression pattern for an
131 * Ensembl protein stable identifier
136 public boolean isProteinIdentifier(String query)
138 return query == null ? false : PROTEIN_REGEX.search(query);
142 * Answers true if the query matches the regular expression pattern for an
143 * Ensembl gene stable identifier
148 public boolean isGeneIdentifier(String query)
150 return query == null ? false : GENE_REGEX.search(query);
154 public boolean queryInProgress()
160 public StringBuffer getRawRecords()
166 * Returns the URL for the client http request
170 * @throws MalformedURLException
172 protected abstract URL getUrl(List<String> ids)
173 throws MalformedURLException;
176 * Returns true if client uses GET method, false if it uses POST
180 protected abstract boolean useGetRequest();
183 * Return the desired value for the Content-Type request header
188 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
190 protected abstract String getRequestMimeType(boolean multipleIds);
193 * Return the desired value for the Accept request header
196 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
198 protected abstract String getResponseMimeType();
201 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
202 * indicates available, else false
204 * @see http://rest.ensembl.org/documentation/info/ping
207 private boolean checkEnsembl()
209 BufferedReader br = null;
212 // note this format works for both ensembl and ensemblgenomes
213 // info/ping.json works for ensembl only (March 2016)
214 URL ping = new URL(getDomain()
215 + "/info/ping?content-type=application/json");
218 * expect {"ping":1} if ok
219 * if ping takes more than 2 seconds to respond, treat as if unavailable
221 br = getHttpResponse(ping, null, 2 * 1000);
222 JSONParser jp = new JSONParser();
223 JSONObject val = (JSONObject) jp.parse(br);
224 String pingString = val.get("ping").toString();
225 return pingString != null;
226 } catch (Throwable t)
228 System.err.println("Error connecting to " + PING_URL + ": "
237 } catch (IOException e)
247 * returns a reader to a Fasta response from the Ensembl sequence endpoint
251 * @throws IOException
253 protected FileParse getSequenceReader(List<String> ids)
256 URL url = getUrl(ids);
258 BufferedReader reader = getHttpResponse(url, ids);
264 FileParse fp = new FileParse(reader, url.toString(), DataSourceType.URL);
269 * Gets a reader to the HTTP response, using the default read timeout of 5
275 * @throws IOException
277 protected BufferedReader getHttpResponse(URL url, List<String> ids)
280 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
284 * Writes the HTTP request and gets the response as a reader.
288 * written as Json POST body if more than one
292 * @throws IOException
293 * if response code was not 200, or other I/O error
295 protected BufferedReader getHttpResponse(URL url, List<String> ids,
296 int readTimeout) throws IOException
298 // long now = System.currentTimeMillis();
299 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
302 * POST method allows multiple queries in one request; it is supported for
303 * sequence queries, but not for overlap
305 boolean multipleIds = ids != null && ids.size() > 1;
306 connection.setRequestMethod(multipleIds ? HttpMethod.POST
308 connection.setRequestProperty("Content-Type",
309 getRequestMimeType(multipleIds));
310 connection.setRequestProperty("Accept", getResponseMimeType());
312 connection.setUseCaches(false);
313 connection.setDoInput(true);
314 connection.setDoOutput(multipleIds);
316 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
317 connection.setReadTimeout(readTimeout);
321 writePostBody(connection, ids);
324 int responseCode = connection.getResponseCode();
326 if (responseCode != 200)
329 * note: a GET request for an invalid id returns an error code e.g. 415
330 * but POST request returns 200 and an empty Fasta response
332 System.err.println("Response code " + responseCode + " for " + url);
336 InputStream response = connection.getInputStream();
338 // System.out.println(getClass().getName() + " took "
339 // + (System.currentTimeMillis() - now) + "ms to fetch");
341 checkRateLimits(connection);
343 BufferedReader reader = null;
344 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
349 * Inspect response headers for any sign of server overload and respect any
350 * 'retry-after' directive
352 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
355 void checkRateLimits(HttpURLConnection connection)
357 // number of requests allowed per time interval:
358 String limit = connection.getHeaderField("X-RateLimit-Limit");
359 // length of quota time interval in seconds:
360 // String period = connection.getHeaderField("X-RateLimit-Period");
361 // seconds remaining until usage quota is reset:
362 String reset = connection.getHeaderField("X-RateLimit-Reset");
363 // number of requests remaining from quota for current period:
364 String remaining = connection.getHeaderField("X-RateLimit-Remaining");
365 // number of seconds to wait before retrying (if remaining == 0)
366 String retryDelay = connection.getHeaderField("Retry-After");
371 EnsemblInfo info = domainData.get(getDomain());
372 if (retryDelay != null)
374 System.err.println("Ensembl REST service rate limit exceeded, wait "
375 + retryDelay + " seconds before retrying");
378 info.retryAfter = System.currentTimeMillis()
379 + (1000 * Integer.valueOf(retryDelay));
380 } catch (NumberFormatException e)
382 System.err.println("Unexpected value for Retry-After: "
390 // System.out.println(String.format(
391 // "%s Ensembl requests remaining of %s (reset in %ss)",
392 // remaining, limit, reset));
397 * Rechecks if Ensembl is responding, unless the last check was successful and
398 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
399 * else false. Also retrieves and saves the current version of Ensembl data
400 * and REST services at intervals.
404 protected boolean isEnsemblAvailable()
406 EnsemblInfo info = domainData.get(getDomain());
408 long now = System.currentTimeMillis();
411 * check if we are waiting for 'Retry-After' to expire
413 if (info.retryAfter > now)
415 System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
416 + " secs to wait before retrying Ensembl");
425 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
427 boolean retestAvailability = (now - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
428 if (!info.restAvailable || retestAvailability)
430 info.restAvailable = checkEnsembl();
431 info.lastAvailableCheckTime = now;
435 * refetch Ensembl versions if the recheck period has elapsed
437 boolean refetchVersion = (now - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
440 checkEnsemblRestVersion();
441 checkEnsemblDataVersion();
442 info.lastVersionCheckTime = now;
445 return info.restAvailable;
449 * Constructs, writes and flushes the POST body of the request, containing the
450 * query ids in JSON format
454 * @throws IOException
456 protected void writePostBody(HttpURLConnection connection,
457 List<String> ids) throws IOException
460 StringBuilder postBody = new StringBuilder(64);
461 postBody.append("{\"ids\":[");
463 for (String id : ids)
467 postBody.append(",");
470 postBody.append("\"");
471 postBody.append(id.trim());
472 postBody.append("\"");
474 postBody.append("]}");
475 byte[] thepostbody = postBody.toString().getBytes();
476 connection.setRequestProperty("Content-Length",
477 Integer.toString(thepostbody.length));
478 DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
479 wr.write(thepostbody);
485 * Fetches and checks Ensembl's REST version number
489 private void checkEnsemblRestVersion()
491 EnsemblInfo info = domainData.get(getDomain());
493 JSONParser jp = new JSONParser();
497 url = new URL(getDomain()
498 + "/info/rest?content-type=application/json");
499 BufferedReader br = getHttpResponse(url, null);
500 JSONObject val = (JSONObject) jp.parse(br);
501 String version = val.get("release").toString();
502 String majorVersion = version.substring(0, version.indexOf("."));
503 String expected = info.expectedRestVersion;
504 String expectedMajorVersion = expected.substring(0,
505 expected.indexOf("."));
506 info.restMajorVersionMismatch = false;
510 * if actual REST major version is ahead of what we expect,
511 * record this in case we want to warn the user
513 if (Float.valueOf(majorVersion) > Float
514 .valueOf(expectedMajorVersion))
516 info.restMajorVersionMismatch = true;
518 } catch (NumberFormatException e)
520 System.err.println("Error in REST version: " + e.toString());
524 * check if REST version is later than what Jalview has tested against,
525 * if so warn; we don't worry if it is earlier (this indicates Jalview has
526 * been tested in advance against the next pending REST version)
528 boolean laterVersion = StringUtils.compareVersions(version, expected) == 1;
533 .format("EnsemblRestClient expected %s REST version %s but found %s, see %s",
534 getDbSource(), expected, version,
537 info.restVersion = version;
538 } catch (Throwable t)
540 System.err.println("Error checking Ensembl REST version: "
545 public boolean isRestMajorVersionMismatch()
547 return domainData.get(getDomain()).restMajorVersionMismatch;
551 * Fetches and checks Ensembl's data version number
555 private void checkEnsemblDataVersion()
557 JSONParser jp = new JSONParser();
561 url = new URL(getDomain()
562 + "/info/data?content-type=application/json");
563 BufferedReader br = getHttpResponse(url, null);
564 JSONObject val = (JSONObject) jp.parse(br);
565 JSONArray versions = (JSONArray) val.get("releases");
566 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
567 } catch (Throwable t)
569 System.err.println("Error checking Ensembl data version: "
574 public String getEnsemblDataVersion()
576 return domainData.get(getDomain()).dataVersion;
580 public String getDbVersion()
582 return getEnsemblDataVersion();