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.FileParse;
24 import jalview.util.StringUtils;
26 import java.io.BufferedReader;
27 import java.io.DataOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.net.HttpURLConnection;
32 import java.net.MalformedURLException;
34 import java.util.HashMap;
35 import java.util.List;
38 import javax.ws.rs.HttpMethod;
40 import org.json.simple.JSONArray;
41 import org.json.simple.JSONObject;
42 import org.json.simple.parser.JSONParser;
45 * Base class for Ensembl REST service clients
49 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
51 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
53 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
56 * update these constants when Jalview has been checked / updated for
57 * changes to Ensembl REST API
58 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
59 * @see http://rest.ensembl.org/info/rest?content-type=application/json
61 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "4.6";
63 private static final String LATEST_ENSEMBL_REST_VERSION = "4.7";
65 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
67 private static Map<String, EnsemblInfo> domainData;
69 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
70 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
72 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
74 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
78 domainData = new HashMap<String, EnsemblInfo>();
79 domainData.put(ENSEMBL_REST, new EnsemblInfo(ENSEMBL_REST,
80 LATEST_ENSEMBL_REST_VERSION));
81 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
82 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
85 protected volatile boolean inProgress = false;
88 * Default constructor to use rest.ensembl.org
90 public EnsemblRestClient()
96 * Constructor given the target domain to fetch data from
100 public EnsemblRestClient(String d)
106 public boolean queryInProgress()
112 public StringBuffer getRawRecords()
118 * Returns the URL for the client http request
122 * @throws MalformedURLException
124 protected abstract URL getUrl(List<String> ids)
125 throws MalformedURLException;
128 * Returns true if client uses GET method, false if it uses POST
132 protected abstract boolean useGetRequest();
135 * Return the desired value for the Content-Type request header
140 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
142 protected abstract String getRequestMimeType(boolean multipleIds);
145 * Return the desired value for the Accept request header
148 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
150 protected abstract String getResponseMimeType();
153 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
154 * indicates available, else false
156 * @see http://rest.ensembl.org/documentation/info/ping
159 private boolean checkEnsembl()
161 BufferedReader br = null;
164 // note this format works for both ensembl and ensemblgenomes
165 // info/ping.json works for ensembl only (March 2016)
166 URL ping = new URL(getDomain()
167 + "/info/ping?content-type=application/json");
170 * expect {"ping":1} if ok
171 * if ping takes more than 2 seconds to respond, treat as if unavailable
173 br = getHttpResponse(ping, null, 2 * 1000);
176 // error reponse status
179 JSONParser jp = new JSONParser();
180 JSONObject val = (JSONObject) jp.parse(br);
181 String pingString = val.get("ping").toString();
182 return pingString != null;
183 } catch (Throwable t)
185 System.err.println("Error connecting to " + PING_URL + ": "
194 } catch (IOException e)
204 * returns a reader to a Fasta response from the Ensembl sequence endpoint
208 * @throws IOException
210 protected FileParse getSequenceReader(List<String> ids)
213 URL url = getUrl(ids);
215 BufferedReader reader = getHttpResponse(url, ids);
221 FileParse fp = new FileParse(reader, url.toString(), "HTTP_POST");
226 * Gets a reader to the HTTP response, using the default read timeout of 5
232 * @throws IOException
234 protected BufferedReader getHttpResponse(URL url, List<String> ids)
237 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
241 * Writes the HTTP request and gets the response as a reader.
245 * written as Json POST body if more than one
249 * @throws IOException
250 * if response code was not 200, or other I/O error
252 protected BufferedReader getHttpResponse(URL url, List<String> ids,
253 int readTimeout) throws IOException
255 // long now = System.currentTimeMillis();
256 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
259 * POST method allows multiple queries in one request; it is supported for
260 * sequence queries, but not for overlap
262 boolean multipleIds = ids != null && ids.size() > 1;
263 connection.setRequestMethod(multipleIds ? HttpMethod.POST
265 connection.setRequestProperty("Content-Type",
266 getRequestMimeType(multipleIds));
267 connection.setRequestProperty("Accept", getResponseMimeType());
269 connection.setUseCaches(false);
270 connection.setDoInput(true);
271 connection.setDoOutput(multipleIds);
273 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
274 connection.setReadTimeout(readTimeout);
278 writePostBody(connection, ids);
281 int responseCode = connection.getResponseCode();
283 if (responseCode != 200)
286 * note: a GET request for an invalid id returns an error code e.g. 415
287 * but POST request returns 200 and an empty Fasta response
289 System.err.println("Response code " + responseCode + " for " + url);
293 InputStream response = connection.getInputStream();
295 // System.out.println(getClass().getName() + " took "
296 // + (System.currentTimeMillis() - now) + "ms to fetch");
298 checkRateLimits(connection);
300 BufferedReader reader = null;
301 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
306 * Inspect response headers for any sign of server overload and respect any
307 * 'retry-after' directive
309 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
312 void checkRateLimits(HttpURLConnection connection)
314 // number of requests allowed per time interval:
315 // String limit = connection.getHeaderField("X-RateLimit-Limit");
316 // length of quota time interval in seconds:
317 // String period = connection.getHeaderField("X-RateLimit-Period");
318 // seconds remaining until usage quota is reset:
319 // String reset = connection.getHeaderField("X-RateLimit-Reset");
320 // number of requests remaining from quota for current period:
321 // String remaining = connection.getHeaderField("X-RateLimit-Remaining");
322 // number of seconds to wait before retrying (if remaining == 0)
323 String retryDelay = connection.getHeaderField("Retry-After");
328 EnsemblInfo info = domainData.get(getDomain());
329 if (retryDelay != null)
331 System.err.println("Ensembl REST service rate limit exceeded, wait "
332 + retryDelay + " seconds before retrying");
335 info.retryAfter = System.currentTimeMillis()
336 + (1000 * Integer.valueOf(retryDelay));
337 } catch (NumberFormatException e)
339 System.err.println("Unexpected value for Retry-After: "
347 // System.out.println(String.format(
348 // "%s Ensembl requests remaining of %s (reset in %ss)",
349 // remaining, limit, reset));
354 * Rechecks if Ensembl is responding, unless the last check was successful and
355 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
356 * else false. Also retrieves and saves the current version of Ensembl data
357 * and REST services at intervals.
361 protected boolean isEnsemblAvailable()
363 EnsemblInfo info = domainData.get(getDomain());
365 long now = System.currentTimeMillis();
368 * check if we are waiting for 'Retry-After' to expire
370 if (info.retryAfter > now)
372 System.err.println("Still " + (1 + (info.retryAfter - now) / 1000)
373 + " secs to wait before retrying Ensembl");
382 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
384 boolean retestAvailability = (now - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
385 if (!info.restAvailable || retestAvailability)
387 info.restAvailable = checkEnsembl();
388 info.lastAvailableCheckTime = now;
392 * refetch Ensembl versions if the recheck period has elapsed
394 boolean refetchVersion = (now - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
397 checkEnsemblRestVersion();
398 checkEnsemblDataVersion();
399 info.lastVersionCheckTime = now;
402 return info.restAvailable;
406 * Constructs, writes and flushes the POST body of the request, containing the
407 * query ids in JSON format
411 * @throws IOException
413 protected void writePostBody(HttpURLConnection connection,
414 List<String> ids) throws IOException
417 StringBuilder postBody = new StringBuilder(64);
418 postBody.append("{\"ids\":[");
420 for (String id : ids)
424 postBody.append(",");
427 postBody.append("\"");
428 postBody.append(id.trim());
429 postBody.append("\"");
431 postBody.append("]}");
432 byte[] thepostbody = postBody.toString().getBytes();
433 connection.setRequestProperty("Content-Length",
434 Integer.toString(thepostbody.length));
435 DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
436 wr.write(thepostbody);
442 * Fetches and checks Ensembl's REST version number
446 private void checkEnsemblRestVersion()
448 EnsemblInfo info = domainData.get(getDomain());
450 JSONParser jp = new JSONParser();
454 url = new URL(getDomain()
455 + "/info/rest?content-type=application/json");
456 BufferedReader br = getHttpResponse(url, null);
461 JSONObject val = (JSONObject) jp.parse(br);
462 String version = val.get("release").toString();
463 String majorVersion = version.substring(0, version.indexOf("."));
464 String expected = info.expectedRestVersion;
465 String expectedMajorVersion = expected.substring(0,
466 expected.indexOf("."));
467 info.restMajorVersionMismatch = false;
471 * if actual REST major version is ahead of what we expect,
472 * record this in case we want to warn the user
474 if (Float.valueOf(majorVersion) > Float
475 .valueOf(expectedMajorVersion))
477 info.restMajorVersionMismatch = true;
479 } catch (NumberFormatException e)
481 System.err.println("Error in REST version: " + e.toString());
485 * check if REST version is later than what Jalview has tested against,
486 * if so warn; we don't worry if it is earlier (this indicates Jalview has
487 * been tested in advance against the next pending REST version)
489 boolean laterVersion = StringUtils.compareVersions(version, expected) == 1;
492 System.err.println(String.format(
493 "Expected %s REST version %s but found %s, see %s",
494 getDbSource(), expected, version, REST_CHANGE_LOG));
496 info.restVersion = version;
497 } catch (Throwable t)
499 System.err.println("Error checking Ensembl REST version: "
504 public boolean isRestMajorVersionMismatch()
506 return domainData.get(getDomain()).restMajorVersionMismatch;
510 * Fetches and checks Ensembl's data version number
514 private void checkEnsemblDataVersion()
516 JSONParser jp = new JSONParser();
520 url = new URL(getDomain()
521 + "/info/data?content-type=application/json");
522 BufferedReader br = getHttpResponse(url, null);
525 JSONObject val = (JSONObject) jp.parse(br);
526 JSONArray versions = (JSONArray) val.get("releases");
527 domainData.get(getDomain()).dataVersion = versions.get(0)
530 } catch (Throwable t)
532 System.err.println("Error checking Ensembl data version: "
537 public String getEnsemblDataVersion()
539 return domainData.get(getDomain()).dataVersion;
543 public String getDbVersion()
545 return getEnsemblDataVersion();