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.DataOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.HttpURLConnection;
27 import java.net.MalformedURLException;
28 import java.net.ProtocolException;
30 import java.util.HashMap;
31 import java.util.List;
34 import javax.ws.rs.HttpMethod;
36 import org.json.simple.parser.ParseException;
38 import jalview.bin.Cache;
39 import jalview.util.Platform;
40 import jalview.util.StringUtils;
43 * Base class for Ensembl REST service clients
47 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
49 private static final int HTTP_OK = 200;
51 private static final int HTTP_OVERLOAD = 429;
55 Platform.addJ2SDirectDatabaseCall("http://rest.ensembl");
56 Platform.addJ2SDirectDatabaseCall("https://rest.ensembl");
60 * constants for http retries and timeout;
61 * not final so they can be changed by a Groovy script
63 private static int PING_TIMEOUT_MS = 2 * 1000;
65 private static long PING_RETEST_INTERVAL = 10 * 1000L; // 10 seconds
67 private static int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
69 private static int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
71 private static int MAX_RETRIES = 3;
74 * update these constants when Jalview has been checked / updated for
75 * changes to Ensembl REST API, and updated JAL-3018
76 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
77 * @see http://rest.ensembl.org/info/rest?content-type=application/json
79 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "12.0";
81 private static final String LATEST_ENSEMBL_REST_VERSION = "12.0";
83 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
85 private static Map<String, EnsemblData> domainData;
87 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
89 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
93 domainData = new HashMap<>();
94 domainData.put(DEFAULT_ENSEMBL_BASEURL, new EnsemblData(
95 DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
96 domainData.put(DEFAULT_ENSEMBL_GENOMES_BASEURL,
97 new EnsemblData(DEFAULT_ENSEMBL_GENOMES_BASEURL,
98 LATEST_ENSEMBLGENOMES_REST_VERSION));
101 protected volatile boolean inProgress = false;
104 * Default constructor to use rest.ensembl.org
106 public EnsemblRestClient()
111 * initialise domain info lazily
113 if (!domainData.containsKey(ensemblDomain))
115 domainData.put(ensemblDomain,
116 new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
118 if (!domainData.containsKey(ensemblGenomesDomain))
120 domainData.put(ensemblGenomesDomain, new EnsemblData(
121 ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
126 * Constructor given the target domain to fetch data from
130 public EnsemblRestClient(String d)
136 public boolean queryInProgress()
142 public StringBuffer getRawRecords()
148 * Returns the URL for the client http request
152 * @throws MalformedURLException
154 protected abstract URL getUrl(List<String> ids)
155 throws MalformedURLException;
158 * Returns true if client uses GET method, false if it uses POST
162 protected abstract boolean useGetRequest();
165 * Returns the desired value for the Content-Type request header. Default is
166 * application/json, override if required to vary this.
169 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
171 protected String getRequestMimeType()
173 return "application/json";
177 * Return the desired value for the Accept request header. Default is
178 * application/json, override if required to vary this.
181 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
183 protected String getResponseMimeType()
185 return "application/json";
189 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
190 * indicates available, else false
192 * @see http://rest.ensembl.org/documentation/info/ping
195 boolean checkEnsembl()
197 String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
198 for (int i = 0 ; i < MAX_RETRIES ; i++)
200 if (pingEnsembl(pingUrl))
204 Cache.log.info("Ensembl ping responded on attempt " + (i+1));
209 Cache.log.error("Ensembl ping failed after " + MAX_RETRIES + " retries");
214 * Connects to Ensembl REST service's 'ping' URL and answers true if
215 * successful, false if no reply, or no reply within the 2 second timeout
220 @SuppressWarnings("unchecked")
221 protected boolean pingEnsembl(String pingUrl)
225 // note this format works for both ensembl and ensemblgenomes
226 // info/ping.json works for ensembl only (March 2016)
229 * expect {"ping":1} if ok
230 * if ping takes more than 2 seconds to respond, treat as if unavailable
232 Map<String, Object> val = (Map<String, Object>) getJSON(
233 new URL(pingUrl), null, PING_TIMEOUT_MS, MODE_MAP, null);
238 String pingString = val.get("ping").toString();
239 return pingString != null;
240 } catch (Throwable t)
243 "Error connecting to " + pingUrl + ": " + t.getMessage());
248 protected final static int MODE_ARRAY = 0;
250 protected final static int MODE_MAP = 1;
252 protected final static int MODE_ITERATOR = 2;
255 // * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
256 // * If the request failed the return value may be null.
260 // * @throws IOException
261 // * @throws ParseException
263 // protected Object getSequenceJSON(List<String> ids, int mode)
264 // throws IOException, ParseException
266 // URL url = getUrl(ids);
267 // return getJSON(url, ids, -1, mode);
271 // * Gets a reader to the HTTP response, using the default read timeout of 5
277 // * @throws IOException
279 // protected BufferedReader getHttpResponse(URL url, List<String> ids)
280 // throws IOException
282 // return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
286 * Sends the HTTP request and gets the response as a reader. Returns null if
287 * the HTTP response code was not 200.
291 * written as Json POST body if more than one
295 * @throws IOException
296 * @throws ParseException
298 private Object getJSON(URL url, List<String> ids, int readTimeout)
299 throws IOException, ParseException
304 readTimeout = DEFAULT_READ_TIMEOUT;
306 int retriesLeft = MAX_RETRIES;
307 HttpURLConnection connection = null;
308 int responseCode = 0;
310 Platform.setAjaxJSON(url);
312 while (retriesLeft > 0)
314 connection = tryConnection(url, ids, readTimeout);
315 responseCode = connection.getResponseCode();
316 if (responseCode == HTTP_OVERLOAD) // 429
319 checkRetryAfter(connection);
326 if (responseCode != HTTP_OK) // 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 Cache.log.error("Response code " + responseCode);// + " for " + url);
336 InputStream response = connection.getInputStream();
338 // Platform.timeCheck(null, Platform.TIME_MARK);
339 Object ret = Platform.parseJSON(response);
340 // Platform.timeCheck("EnsemblRestClient.getJSON " + url,
341 // Platform.TIME_MARK);
351 * @throws IOException
352 * @throws ProtocolException
354 protected HttpURLConnection tryConnection(URL url, List<String> ids,
355 int readTimeout) throws IOException, ProtocolException
357 // 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", getRequestMimeType());
369 connection.setRequestProperty("Accept", getResponseMimeType());
371 connection.setDoInput(true);
372 connection.setDoOutput(multipleIds);
374 connection.setUseCaches(false);
375 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
376 connection.setReadTimeout(readTimeout);
380 writePostBody(connection, ids);
386 * Inspects response headers for a 'retry-after' directive, and waits for the
387 * directed period (if less than 10 seconds)
389 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
392 void checkRetryAfter(HttpURLConnection connection)
394 String retryDelay = connection.getHeaderField("Retry-After");
399 if (retryDelay != null)
403 int retrySecs = Integer.valueOf(retryDelay);
404 if (retrySecs > 0 && retrySecs < 10)
407 "Ensembl REST service rate limit exceeded, waiting "
408 + retryDelay + " seconds before retrying");
409 Thread.sleep(1000 * retrySecs);
411 } catch (NumberFormatException | InterruptedException e)
413 System.err.println("Error handling Retry-After: " + e.getMessage());
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 EnsemblData info = domainData.get(getDomain());
430 long now = System.currentTimeMillis();
433 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
435 boolean retestAvailability = (now
436 - info.lastAvailableCheckTime) > PING_RETEST_INTERVAL;
437 if (!info.restAvailable || retestAvailability)
439 info.restAvailable = checkEnsembl();
440 info.lastAvailableCheckTime = now;
444 * refetch Ensembl versions if the recheck period has elapsed
446 boolean refetchVersion = (now
447 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
450 checkEnsemblRestVersion();
451 checkEnsemblDataVersion();
452 info.lastVersionCheckTime = now;
455 return info.restAvailable;
459 * Constructs, writes and flushes the POST body of the request, containing the
460 * query ids in JSON format
464 * @throws IOException
466 protected void writePostBody(HttpURLConnection connection,
467 List<String> ids) throws IOException
470 StringBuilder postBody = new StringBuilder(64);
471 postBody.append("{\"ids\":[");
473 for (int i = 0, n = ids.size(); i < n; i++)
475 String id = ids.get(i);
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 * Primary access point to parsed JSON data, including the call to retrieve
501 * request url; if null, getUrl(ids) will be used
503 * optional; may be null
505 * -1 for default delay
507 * map, array, or array iterator
509 * an optional key for an outer map
510 * @return a Map, List, Iterator, or null
511 * @throws IOException
512 * @throws ParseException
514 * @author Bob Hanson 2019
516 @SuppressWarnings("unchecked")
517 protected Object getJSON(URL url, List<String> ids, int msDelay, int mode,
518 String mapKey) throws IOException, ParseException
525 Object json = (url == null ? null : getJSON(url, ids, msDelay));
527 if (json != null && mapKey != null)
529 json = ((Map<String, Object>) json).get(mapKey);
541 json = ((List<Object>) json).iterator();
548 * Fetches and checks Ensembl's REST version number
552 @SuppressWarnings("unchecked")
553 private void checkEnsemblRestVersion()
555 EnsemblData info = domainData.get(getDomain());
559 Map<String, Object> val = (Map<String, Object>) getJSON(
560 new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON), null,
566 String version = val.get("release").toString();
567 String majorVersion = version.substring(0, version.indexOf("."));
568 String expected = info.expectedRestVersion;
569 String expectedMajorVersion = expected.substring(0,
570 expected.indexOf("."));
571 info.restMajorVersionMismatch = false;
575 * if actual REST major version is ahead of what we expect,
576 * record this in case we want to warn the user
578 if (Float.valueOf(majorVersion) > Float
579 .valueOf(expectedMajorVersion))
581 info.restMajorVersionMismatch = true;
583 } catch (NumberFormatException e)
585 System.err.println("Error in REST version: " + e.toString());
589 * check if REST version is later than what Jalview has tested against,
590 * if so warn; we don't worry if it is earlier (this indicates Jalview has
591 * been tested in advance against the next pending REST version)
593 boolean laterVersion = StringUtils.compareVersions(version,
597 System.err.println(String.format(
598 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
599 getDbSource(), expected, version, REST_CHANGE_LOG));
601 info.restVersion = version;
602 } catch (Throwable t)
605 "Error checking Ensembl REST version: " + t.getMessage());
609 public boolean isRestMajorVersionMismatch()
611 return domainData.get(getDomain()).restMajorVersionMismatch;
615 * Fetches and checks Ensembl's data version number
619 @SuppressWarnings("unchecked")
620 private void checkEnsemblDataVersion()
622 Map<String, Object> val;
625 val = (Map<String, Object>) getJSON(
626 new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON), null,
632 List<Object> versions = (List<Object>) val.get("releases");
633 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
634 } catch (Throwable e)
635 {// could be IOException | ParseException e) {
637 "Error checking Ensembl data version: " + e.getMessage());
641 public String getEnsemblDataVersion()
643 return domainData.get(getDomain()).dataVersion;
647 public String getDbVersion()
649 return getEnsemblDataVersion();