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 java.io.BufferedReader;
24 import java.io.DataOutputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.net.HttpURLConnection;
28 import java.net.MalformedURLException;
29 import java.net.ProtocolException;
31 import java.util.HashMap;
32 import java.util.List;
35 import javax.ws.rs.HttpMethod;
37 import org.json.simple.parser.ParseException;
39 import jalview.util.Platform;
40 import jalview.util.StringUtils;
43 * Base class for Ensembl REST service clients
47 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
52 Platform.addJ2SDirectDatabaseCall("http://rest.ensembl");
53 Platform.addJ2SDirectDatabaseCall("https://rest.ensembl");
56 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
58 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
60 private static final int MAX_RETRIES = 3;
62 private static final int HTTP_OK = 200;
64 private static final int HTTP_OVERLOAD = 429;
67 * update these constants when Jalview has been checked / updated for
68 * changes to Ensembl REST API, and updated JAL-3018
69 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
70 * @see http://rest.ensembl.org/info/rest?content-type=application/json
72 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "15.2";
74 private static final String LATEST_ENSEMBL_REST_VERSION = "15.2";
76 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
78 private static Map<String, EnsemblData> domainData;
80 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
82 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
84 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
88 domainData = new HashMap<>();
89 domainData.put(DEFAULT_ENSEMBL_BASEURL, new EnsemblData(
90 DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
91 domainData.put(DEFAULT_ENSEMBL_GENOMES_BASEURL,
92 new EnsemblData(DEFAULT_ENSEMBL_GENOMES_BASEURL,
93 LATEST_ENSEMBLGENOMES_REST_VERSION));
96 protected volatile boolean inProgress = false;
99 * Default constructor to use rest.ensembl.org
101 public EnsemblRestClient()
106 * initialise domain info lazily
108 if (!domainData.containsKey(ensemblDomain))
110 domainData.put(ensemblDomain,
111 new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
113 if (!domainData.containsKey(ensemblGenomesDomain))
115 domainData.put(ensemblGenomesDomain, new EnsemblData(
116 ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
121 * Constructor given the target domain to fetch data from
125 public EnsemblRestClient(String d)
131 public boolean queryInProgress()
137 public StringBuffer getRawRecords()
143 * Returns the URL for the client http request
147 * @throws MalformedURLException
149 protected abstract URL getUrl(List<String> ids)
150 throws MalformedURLException;
153 * Returns true if client uses GET method, false if it uses POST
157 protected abstract boolean useGetRequest();
160 * Returns the desired value for the Content-Type request header. Default is
161 * application/json, override if required to vary this.
164 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
166 protected String getRequestMimeType()
168 return "application/json";
172 * Return the desired value for the Accept request header. Default is
173 * application/json, override if required to vary this.
176 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
178 protected String getResponseMimeType()
180 return "application/json";
184 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
185 * indicates available, else false
187 * @see http://rest.ensembl.org/documentation/info/ping
190 @SuppressWarnings("unchecked")
191 boolean checkEnsembl()
193 BufferedReader br = null;
194 String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
197 // note this format works for both ensembl and ensemblgenomes
198 // info/ping.json works for ensembl only (March 2016)
201 * expect {"ping":1} if ok
202 * if ping takes more than 2 seconds to respond, treat as if unavailable
204 Map<String, Object> val = (Map<String, Object>) getJSON(
205 new URL(pingUrl), null, 2 * 1000, MODE_MAP, null);
210 String pingString = val.get("ping").toString();
211 return pingString != null;
212 } catch (Throwable t)
214 jalview.bin.Console.errPrintln(
215 "Error connecting to " + pingUrl + ": " + t.getMessage());
223 } catch (IOException e)
232 protected final static int MODE_ARRAY = 0;
234 protected final static int MODE_MAP = 1;
236 protected final static int MODE_ITERATOR = 2;
239 // * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
240 // * If the request failed the return value may be null.
244 // * @throws IOException
245 // * @throws ParseException
247 // protected Object getSequenceJSON(List<String> ids, int mode)
248 // throws IOException, ParseException
250 // URL url = getUrl(ids);
251 // return getJSON(url, ids, -1, mode);
255 // * Gets a reader to the HTTP response, using the default read timeout of 5
261 // * @throws IOException
263 // protected BufferedReader getHttpResponse(URL url, List<String> ids)
264 // throws IOException
266 // return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
270 * Sends the HTTP request and gets the response as a reader. Returns null if
271 * the HTTP response code was not 200.
275 * written as Json POST body if more than one
279 * @throws IOException
280 * @throws ParseException
282 private Object getJSON(URL url, List<String> ids, int readTimeout)
283 throws IOException, ParseException
288 readTimeout = DEFAULT_READ_TIMEOUT;
290 int retriesLeft = MAX_RETRIES;
291 HttpURLConnection connection = null;
292 int responseCode = 0;
294 Platform.setAjaxJSON(url);
296 while (retriesLeft > 0)
298 connection = tryConnection(url, ids, readTimeout);
299 responseCode = connection.getResponseCode();
300 if (responseCode == HTTP_OVERLOAD) // 429
303 checkRetryAfter(connection);
310 if (responseCode != HTTP_OK) // 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 jalview.bin.Console.errPrintln("Response code " + responseCode);// + " for " + url);
320 InputStream response = connection.getInputStream();
322 // Platform.timeCheck(null, Platform.TIME_MARK);
323 Object ret = Platform.parseJSON(response);
324 // Platform.timeCheck("EnsemblRestClient.getJSON " + url,
325 // Platform.TIME_MARK);
335 * @throws IOException
336 * @throws ProtocolException
338 protected HttpURLConnection tryConnection(URL url, List<String> ids,
339 int readTimeout) throws IOException, ProtocolException
341 // jalview.bin.Console.outPrintln(System.currentTimeMillis() + " " + url);
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", getRequestMimeType());
353 connection.setRequestProperty("Accept", getResponseMimeType());
355 connection.setDoInput(true);
356 connection.setDoOutput(multipleIds);
358 connection.setUseCaches(false);
359 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
360 connection.setReadTimeout(readTimeout);
364 writePostBody(connection, ids);
370 * Inspects response headers for a 'retry-after' directive, and waits for the
371 * directed period (if less than 10 seconds)
373 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
376 void checkRetryAfter(HttpURLConnection connection)
378 String retryDelay = connection.getHeaderField("Retry-After");
383 if (retryDelay != null)
387 int retrySecs = Integer.valueOf(retryDelay);
388 if (retrySecs > 0 && retrySecs < 10)
390 jalview.bin.Console.errPrintln(
391 "Ensembl REST service rate limit exceeded, waiting "
392 + retryDelay + " seconds before retrying");
393 Thread.sleep(1000 * retrySecs);
395 } catch (NumberFormatException | InterruptedException e)
397 jalview.bin.Console.errPrintln("Error handling Retry-After: " + e.getMessage());
403 * Rechecks if Ensembl is responding, unless the last check was successful and
404 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
405 * else false. Also retrieves and saves the current version of Ensembl data
406 * and REST services at intervals.
410 protected boolean isEnsemblAvailable()
412 EnsemblData info = domainData.get(getDomain());
414 long now = System.currentTimeMillis();
417 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
419 boolean retestAvailability = (now
420 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
421 if (!info.restAvailable || retestAvailability)
423 info.restAvailable = checkEnsembl();
424 info.lastAvailableCheckTime = now;
428 * refetch Ensembl versions if the recheck period has elapsed
430 boolean refetchVersion = (now
431 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
434 checkEnsemblRestVersion();
435 checkEnsemblDataVersion();
436 info.lastVersionCheckTime = now;
439 return info.restAvailable;
443 * Constructs, writes and flushes the POST body of the request, containing the
444 * query ids in JSON format
448 * @throws IOException
450 protected void writePostBody(HttpURLConnection connection,
451 List<String> ids) throws IOException
454 StringBuilder postBody = new StringBuilder(64);
455 postBody.append("{\"ids\":[");
457 for (int i = 0, n = ids.size(); i < n; i++)
459 String id = ids.get(i);
462 postBody.append(",");
465 postBody.append("\"");
466 postBody.append(id.trim());
467 postBody.append("\"");
469 postBody.append("]}");
470 byte[] thepostbody = postBody.toString().getBytes();
471 connection.setRequestProperty("Content-Length",
472 Integer.toString(thepostbody.length));
473 DataOutputStream wr = new DataOutputStream(
474 connection.getOutputStream());
475 wr.write(thepostbody);
481 * Primary access point to parsed JSON data, including the call to retrieve
485 * request url; if null, getUrl(ids) will be used
487 * optional; may be null
489 * -1 for default delay
491 * map, array, or array iterator
493 * an optional key for an outer map
494 * @return a Map, List, Iterator, or null
495 * @throws IOException
496 * @throws ParseException
498 * @author Bob Hanson 2019
500 @SuppressWarnings("unchecked")
501 protected Object getJSON(URL url, List<String> ids, int msDelay, int mode,
502 String mapKey) throws IOException, ParseException
509 Object json = (url == null ? null : getJSON(url, ids, msDelay));
511 if (json != null && mapKey != null)
513 json = ((Map<String, Object>) json).get(mapKey);
525 json = ((List<Object>) json).iterator();
532 * Fetches and checks Ensembl's REST version number
536 @SuppressWarnings("unchecked")
537 private void checkEnsemblRestVersion()
539 EnsemblData info = domainData.get(getDomain());
543 Map<String, Object> val = (Map<String, Object>) getJSON(
544 new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON), null,
550 String version = val.get("release").toString();
551 String majorVersion = version.substring(0, version.indexOf("."));
552 String expected = info.expectedRestVersion;
553 String expectedMajorVersion = expected.substring(0,
554 expected.indexOf("."));
555 info.restMajorVersionMismatch = false;
559 * if actual REST major version is ahead of what we expect,
560 * record this in case we want to warn the user
562 if (Float.valueOf(majorVersion) > Float
563 .valueOf(expectedMajorVersion))
565 info.restMajorVersionMismatch = true;
567 } catch (NumberFormatException e)
569 jalview.bin.Console.errPrintln("Error in REST version: " + e.toString());
573 * check if REST version is later than what Jalview has tested against,
574 * if so warn; we don't worry if it is earlier (this indicates Jalview has
575 * been tested in advance against the next pending REST version)
577 boolean laterVersion = StringUtils.compareVersions(version,
581 jalview.bin.Console.errPrintln(String.format(
582 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
583 getDbSource(), expected, version, REST_CHANGE_LOG));
585 info.restVersion = version;
586 } catch (Throwable t)
588 jalview.bin.Console.errPrintln(
589 "Error checking Ensembl REST version: " + t.getMessage());
593 public boolean isRestMajorVersionMismatch()
595 return domainData.get(getDomain()).restMajorVersionMismatch;
599 * Fetches and checks Ensembl's data version number
603 @SuppressWarnings("unchecked")
604 private void checkEnsemblDataVersion()
606 Map<String, Object> val;
609 val = (Map<String, Object>) getJSON(
610 new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON), null,
616 List<Object> versions = (List<Object>) val.get("releases");
617 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
618 } catch (Throwable e)
619 {// could be IOException | ParseException e) {
620 jalview.bin.Console.errPrintln(
621 "Error checking Ensembl data version: " + e.getMessage());
625 public String getEnsemblDataVersion()
627 return domainData.get(getDomain()).dataVersion;
631 public String getDbVersion()
633 return getEnsemblDataVersion();