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
59 private static final int MAX_RETRIES = 3;
61 private static final int HTTP_OK = 200;
63 private static final int HTTP_OVERLOAD = 429;
66 * update these constants when Jalview has been checked / updated for
67 * changes to Ensembl REST API (ref JAL-2105)
68 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
69 * @see http://rest.ensembl.org/info/rest?content-type=application/json
71 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "5.0";
73 private static final String LATEST_ENSEMBL_REST_VERSION = "5.0";
75 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
77 private static Map<String, EnsemblInfo> domainData;
79 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
80 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
82 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
84 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
86 private static final Regex PROTEIN_REGEX = new Regex(
87 "(ENS)([A-Z]{3}|)P[0-9]{11}$");
89 private static final Regex TRANSCRIPT_REGEX = new Regex(
90 "(ENS)([A-Z]{3}|)T[0-9]{11}$");
92 private static final Regex GENE_REGEX = new Regex(
93 "(ENS)([A-Z]{3}|)G[0-9]{11}$");
97 domainData = new HashMap<String, EnsemblInfo>();
98 domainData.put(ENSEMBL_REST,
99 new EnsemblInfo(ENSEMBL_REST, LATEST_ENSEMBL_REST_VERSION));
100 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
101 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
104 protected volatile boolean inProgress = false;
107 * Default constructor to use rest.ensembl.org
109 public EnsemblRestClient()
115 * Constructor given the target domain to fetch data from
119 public EnsemblRestClient(String d)
125 * Answers true if the query matches the regular expression pattern for an
126 * Ensembl transcript stable identifier
131 public boolean isTranscriptIdentifier(String query)
133 return query == null ? false : TRANSCRIPT_REGEX.search(query);
137 * Answers true if the query matches the regular expression pattern for an
138 * Ensembl protein stable identifier
143 public boolean isProteinIdentifier(String query)
145 return query == null ? false : PROTEIN_REGEX.search(query);
149 * Answers true if the query matches the regular expression pattern for an
150 * Ensembl gene stable identifier
155 public boolean isGeneIdentifier(String query)
157 return query == null ? false : GENE_REGEX.search(query);
161 public boolean queryInProgress()
167 public StringBuffer getRawRecords()
173 * Returns the URL for the client http request
177 * @throws MalformedURLException
179 protected abstract URL getUrl(List<String> ids)
180 throws MalformedURLException;
183 * Returns true if client uses GET method, false if it uses POST
187 protected abstract boolean useGetRequest();
190 * Return the desired value for the Content-Type request header
195 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
197 protected abstract String getRequestMimeType(boolean multipleIds);
200 * Return the desired value for the Accept request header
203 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
205 protected abstract String getResponseMimeType();
208 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
209 * indicates available, else false
211 * @see http://rest.ensembl.org/documentation/info/ping
214 boolean checkEnsembl()
216 BufferedReader br = null;
219 // note this format works for both ensembl and ensemblgenomes
220 // info/ping.json works for ensembl only (March 2016)
222 getDomain() + "/info/ping?content-type=application/json");
225 * expect {"ping":1} if ok
226 * if ping takes more than 2 seconds to respond, treat as if unavailable
228 br = getHttpResponse(ping, null, 2 * 1000);
233 JSONParser jp = new JSONParser();
234 JSONObject val = (JSONObject) jp.parse(br);
235 String pingString = val.get("ping").toString();
236 return pingString != null;
237 } catch (Throwable t)
240 "Error connecting to " + PING_URL + ": " + t.getMessage());
248 } catch (IOException e)
258 * returns a reader to a Fasta response from the Ensembl sequence endpoint
262 * @throws IOException
264 protected FileParse getSequenceReader(List<String> ids) throws IOException
266 URL url = getUrl(ids);
268 BufferedReader reader = getHttpResponse(url, ids);
274 FileParse fp = new FileParse(reader, url.toString(),
280 * Gets a reader to the HTTP response, using the default read timeout of 5
286 * @throws IOException
288 protected BufferedReader getHttpResponse(URL url, List<String> ids)
291 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
295 * Sends the HTTP request and gets the response as a reader
299 * written as Json POST body if more than one
303 * @throws IOException
304 * if response code was not 200, or other I/O error
306 protected BufferedReader getHttpResponse(URL url, List<String> ids,
307 int readTimeout) throws IOException
309 int retriesLeft = MAX_RETRIES;
310 HttpURLConnection connection = null;
311 int responseCode = 0;
313 while (retriesLeft > 0)
315 connection = tryConnection(url, ids, readTimeout);
316 responseCode = connection.getResponseCode();
317 if (responseCode == HTTP_OVERLOAD) // 429
320 checkRetryAfter(connection);
327 if (responseCode != HTTP_OK) // 200
330 * note: a GET request for an invalid id returns an error code e.g. 415
331 * but POST request returns 200 and an empty Fasta response
333 System.err.println("Response code " + responseCode + " for " + url);
337 InputStream response = connection.getInputStream();
339 // System.out.println(getClass().getName() + " took "
340 // + (System.currentTimeMillis() - now) + "ms to fetch");
342 BufferedReader reader = null;
343 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
352 * @throws IOException
353 * @throws ProtocolException
355 protected HttpURLConnection tryConnection(URL url, List<String> ids,
356 int readTimeout) throws IOException, ProtocolException
358 // System.out.println(System.currentTimeMillis() + " " + url);
359 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
362 * POST method allows multiple queries in one request; it is supported for
363 * sequence queries, but not for overlap
365 boolean multipleIds = ids != null && ids.size() > 1;
366 connection.setRequestMethod(
367 multipleIds ? HttpMethod.POST : HttpMethod.GET);
368 connection.setRequestProperty("Content-Type",
369 getRequestMimeType(multipleIds));
370 connection.setRequestProperty("Accept", getResponseMimeType());
372 connection.setUseCaches(false);
373 connection.setDoInput(true);
374 connection.setDoOutput(multipleIds);
376 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
377 connection.setReadTimeout(readTimeout);
381 writePostBody(connection, ids);
387 * Inspects response headers for a 'retry-after' directive, and waits for the
388 * directed period (if less than 10 seconds)
390 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
393 void checkRetryAfter(HttpURLConnection connection)
395 String retryDelay = connection.getHeaderField("Retry-After");
400 if (retryDelay != null)
404 int retrySecs = Integer.valueOf(retryDelay);
405 if (retrySecs > 0 && retrySecs < 10)
408 .println("Ensembl REST service rate limit exceeded, waiting "
409 + retryDelay + " seconds before retrying");
410 Thread.sleep(1000 * retrySecs);
412 } catch (NumberFormatException | InterruptedException e)
414 System.err.println("Error handling Retry-After: " + e.getMessage());
420 * Rechecks if Ensembl is responding, unless the last check was successful and
421 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
422 * else false. Also retrieves and saves the current version of Ensembl data
423 * and REST services at intervals.
427 protected boolean isEnsemblAvailable()
429 EnsemblInfo info = domainData.get(getDomain());
431 long now = System.currentTimeMillis();
434 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
436 boolean retestAvailability = (now
437 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
438 if (!info.restAvailable || retestAvailability)
440 info.restAvailable = checkEnsembl();
441 info.lastAvailableCheckTime = now;
445 * refetch Ensembl versions if the recheck period has elapsed
447 boolean refetchVersion = (now
448 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
451 checkEnsemblRestVersion();
452 checkEnsemblDataVersion();
453 info.lastVersionCheckTime = now;
456 return info.restAvailable;
460 * Constructs, writes and flushes the POST body of the request, containing the
461 * query ids in JSON format
465 * @throws IOException
467 protected void writePostBody(HttpURLConnection connection,
468 List<String> ids) throws IOException
471 StringBuilder postBody = new StringBuilder(64);
472 postBody.append("{\"ids\":[");
474 for (String id : ids)
478 postBody.append(",");
481 postBody.append("\"");
482 postBody.append(id.trim());
483 postBody.append("\"");
485 postBody.append("]}");
486 byte[] thepostbody = postBody.toString().getBytes();
487 connection.setRequestProperty("Content-Length",
488 Integer.toString(thepostbody.length));
489 DataOutputStream wr = new DataOutputStream(
490 connection.getOutputStream());
491 wr.write(thepostbody);
497 * Fetches and checks Ensembl's REST version number
501 private void checkEnsemblRestVersion()
503 EnsemblInfo info = domainData.get(getDomain());
505 JSONParser jp = new JSONParser();
510 getDomain() + "/info/rest?content-type=application/json");
511 BufferedReader br = getHttpResponse(url, null);
512 JSONObject val = (JSONObject) jp.parse(br);
513 String version = val.get("release").toString();
514 String majorVersion = version.substring(0, version.indexOf("."));
515 String expected = info.expectedRestVersion;
516 String expectedMajorVersion = expected.substring(0,
517 expected.indexOf("."));
518 info.restMajorVersionMismatch = false;
522 * if actual REST major version is ahead of what we expect,
523 * record this in case we want to warn the user
525 if (Float.valueOf(majorVersion) > Float
526 .valueOf(expectedMajorVersion))
528 info.restMajorVersionMismatch = true;
530 } catch (NumberFormatException e)
532 System.err.println("Error in REST version: " + e.toString());
536 * check if REST version is later than what Jalview has tested against,
537 * if so warn; we don't worry if it is earlier (this indicates Jalview has
538 * been tested in advance against the next pending REST version)
540 boolean laterVersion = StringUtils.compareVersions(version,
544 System.err.println(String.format(
545 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
546 getDbSource(), expected, version, REST_CHANGE_LOG));
548 info.restVersion = version;
549 } catch (Throwable t)
552 "Error checking Ensembl REST version: " + t.getMessage());
556 public boolean isRestMajorVersionMismatch()
558 return domainData.get(getDomain()).restMajorVersionMismatch;
562 * Fetches and checks Ensembl's data version number
566 private void checkEnsemblDataVersion()
568 JSONParser jp = new JSONParser();
570 BufferedReader br = null;
575 getDomain() + "/info/data?content-type=application/json");
576 br = getHttpResponse(url, null);
579 JSONObject val = (JSONObject) jp.parse(br);
580 JSONArray versions = (JSONArray) val.get("releases");
581 domainData.get(getDomain()).dataVersion = versions.get(0)
584 } catch (Throwable t)
587 "Error checking Ensembl data version: " + t.getMessage());
595 } catch (IOException e)
603 public String getEnsemblDataVersion()
605 return domainData.get(getDomain()).dataVersion;
609 public String getDbVersion()
611 return getEnsemblDataVersion();