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.HttpUtils;
40 import jalview.util.Platform;
41 import jalview.util.StringUtils;
44 * Base class for Ensembl REST service clients
48 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
53 Platform.addJ2SDirectDatabaseCall("http://rest.ensembl");
54 Platform.addJ2SDirectDatabaseCall("https://rest.ensembl");
57 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
59 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
61 private static final int MAX_RETRIES = 3;
63 private static final int HTTP_OK = 200;
65 private static final int HTTP_OVERLOAD = 429;
68 * update these constants when Jalview has been checked / updated for
69 * changes to Ensembl REST API, and updated JAL-3018
70 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
71 * @see http://rest.ensembl.org/info/rest?content-type=application/json
73 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "15.2";
75 private static final String LATEST_ENSEMBL_REST_VERSION = "15.2";
77 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
79 private static Map<String, EnsemblData> domainData;
81 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
83 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
85 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
89 domainData = new HashMap<>();
90 domainData.put(DEFAULT_ENSEMBL_BASEURL, new EnsemblData(
91 DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
92 domainData.put(DEFAULT_ENSEMBL_GENOMES_BASEURL,
93 new EnsemblData(DEFAULT_ENSEMBL_GENOMES_BASEURL,
94 LATEST_ENSEMBLGENOMES_REST_VERSION));
97 protected volatile boolean inProgress = false;
100 * Default constructor to use rest.ensembl.org
102 public EnsemblRestClient()
107 * initialise domain info lazily
109 if (!domainData.containsKey(ensemblDomain))
111 domainData.put(ensemblDomain,
112 new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
114 if (!domainData.containsKey(ensemblGenomesDomain))
116 domainData.put(ensemblGenomesDomain, new EnsemblData(
117 ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
122 * Constructor given the target domain to fetch data from
126 public EnsemblRestClient(String d)
132 public boolean queryInProgress()
138 public StringBuffer getRawRecords()
144 * Returns the URL for the client http request
148 * @throws MalformedURLException
150 protected abstract URL getUrl(List<String> ids)
151 throws MalformedURLException;
154 * Returns true if client uses GET method, false if it uses POST
158 protected abstract boolean useGetRequest();
161 * Returns the desired value for the Content-Type request header. Default is
162 * application/json, override if required to vary this.
165 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
167 protected String getRequestMimeType()
169 return "application/json";
173 * Return the desired value for the Accept request header. Default is
174 * application/json, override if required to vary this.
177 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
179 protected String getResponseMimeType()
181 return "application/json";
185 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
186 * indicates available, else false
188 * @see http://rest.ensembl.org/documentation/info/ping
191 @SuppressWarnings("unchecked")
192 boolean checkEnsembl()
194 BufferedReader br = null;
195 String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
198 // note this format works for both ensembl and ensemblgenomes
199 // info/ping.json works for ensembl only (March 2016)
202 * expect {"ping":1} if ok
203 * if ping takes more than 2 seconds to respond, treat as if unavailable
205 Map<String, Object> val = (Map<String, Object>) getJSON(
206 new URL(pingUrl), null, 2 * 1000, MODE_MAP, null);
211 String pingString = val.get("ping").toString();
212 return pingString != null;
213 } catch (Throwable t)
215 jalview.bin.Console.errPrintln(
216 "Error connecting to " + pingUrl + ": " + t.getMessage());
224 } catch (IOException e)
233 protected final static int MODE_ARRAY = 0;
235 protected final static int MODE_MAP = 1;
237 protected final static int MODE_ITERATOR = 2;
240 // * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
241 // * If the request failed the return value may be null.
245 // * @throws IOException
246 // * @throws ParseException
248 // protected Object getSequenceJSON(List<String> ids, int mode)
249 // throws IOException, ParseException
251 // URL url = getUrl(ids);
252 // return getJSON(url, ids, -1, mode);
256 // * Gets a reader to the HTTP response, using the default read timeout of 5
262 // * @throws IOException
264 // protected BufferedReader getHttpResponse(URL url, List<String> ids)
265 // throws IOException
267 // return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
271 * Sends the HTTP request and gets the response as a reader. Returns null if
272 * the HTTP response code was not 200.
276 * written as Json POST body if more than one
280 * @throws IOException
281 * @throws ParseException
283 private Object getJSON(URL url, List<String> ids, int readTimeout)
284 throws IOException, ParseException
289 readTimeout = DEFAULT_READ_TIMEOUT;
291 int retriesLeft = MAX_RETRIES;
292 HttpURLConnection connection = null;
293 int responseCode = 0;
295 Platform.setAjaxJSON(url);
297 while (retriesLeft > 0)
299 connection = tryConnection(url, ids, readTimeout);
300 responseCode = connection.getResponseCode();
301 if (responseCode == HTTP_OVERLOAD) // 429
304 checkRetryAfter(connection);
311 if (responseCode != HTTP_OK) // 200
314 * note: a GET request for an invalid id returns an error code e.g. 415
315 * but POST request returns 200 and an empty Fasta response
317 jalview.bin.Console.errPrintln("Response code " + responseCode);// + " for
323 InputStream response = connection.getInputStream();
325 // Platform.timeCheck(null, Platform.TIME_MARK);
326 Object ret = Platform.parseJSON(response);
327 // Platform.timeCheck("EnsemblRestClient.getJSON " + url,
328 // Platform.TIME_MARK);
338 * @throws IOException
339 * @throws ProtocolException
341 protected HttpURLConnection tryConnection(URL url, List<String> ids,
342 int readTimeout) throws IOException, ProtocolException
344 // jalview.bin.Console.outPrintln(System.currentTimeMillis() + " " + url);
346 HttpURLConnection connection = (HttpURLConnection) HttpUtils
347 .openConnection(url);
350 * POST method allows multiple queries in one request; it is supported for
351 * sequence queries, but not for overlap
353 boolean multipleIds = ids != null && ids.size() > 1;
354 connection.setRequestMethod(
355 multipleIds ? HttpMethod.POST : HttpMethod.GET);
356 connection.setRequestProperty("Content-Type", getRequestMimeType());
357 connection.setRequestProperty("Accept", getResponseMimeType());
359 connection.setDoInput(true);
360 connection.setDoOutput(multipleIds);
362 connection.setUseCaches(false);
363 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
364 connection.setReadTimeout(readTimeout);
368 writePostBody(connection, ids);
374 * Inspects response headers for a 'retry-after' directive, and waits for the
375 * directed period (if less than 10 seconds)
377 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
380 void checkRetryAfter(HttpURLConnection connection)
382 String retryDelay = connection.getHeaderField("Retry-After");
387 if (retryDelay != null)
391 int retrySecs = Integer.valueOf(retryDelay);
392 if (retrySecs > 0 && retrySecs < 10)
394 jalview.bin.Console.errPrintln(
395 "Ensembl REST service rate limit exceeded, waiting "
396 + retryDelay + " seconds before retrying");
397 Thread.sleep(1000 * retrySecs);
399 } catch (NumberFormatException | InterruptedException e)
401 jalview.bin.Console.errPrintln(
402 "Error handling Retry-After: " + e.getMessage());
408 * Rechecks if Ensembl is responding, unless the last check was successful and
409 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
410 * else false. Also retrieves and saves the current version of Ensembl data
411 * and REST services at intervals.
415 protected boolean isEnsemblAvailable()
417 EnsemblData info = domainData.get(getDomain());
419 long now = System.currentTimeMillis();
422 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
424 boolean retestAvailability = (now
425 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
426 if (!info.restAvailable || retestAvailability)
428 info.restAvailable = checkEnsembl();
429 info.lastAvailableCheckTime = now;
433 * refetch Ensembl versions if the recheck period has elapsed
435 boolean refetchVersion = (now
436 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
439 checkEnsemblRestVersion();
440 checkEnsemblDataVersion();
441 info.lastVersionCheckTime = now;
444 return info.restAvailable;
448 * Constructs, writes and flushes the POST body of the request, containing the
449 * query ids in JSON format
453 * @throws IOException
455 protected void writePostBody(HttpURLConnection connection,
456 List<String> ids) throws IOException
459 StringBuilder postBody = new StringBuilder(64);
460 postBody.append("{\"ids\":[");
462 for (int i = 0, n = ids.size(); i < n; i++)
464 String id = ids.get(i);
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(
479 connection.getOutputStream());
480 wr.write(thepostbody);
486 * Primary access point to parsed JSON data, including the call to retrieve
490 * request url; if null, getUrl(ids) will be used
492 * optional; may be null
494 * -1 for default delay
496 * map, array, or array iterator
498 * an optional key for an outer map
499 * @return a Map, List, Iterator, or null
500 * @throws IOException
501 * @throws ParseException
503 * @author Bob Hanson 2019
505 @SuppressWarnings("unchecked")
506 protected Object getJSON(URL url, List<String> ids, int msDelay, int mode,
507 String mapKey) throws IOException, ParseException
514 Object json = (url == null ? null : getJSON(url, ids, msDelay));
516 if (json != null && mapKey != null)
518 json = ((Map<String, Object>) json).get(mapKey);
530 json = ((List<Object>) json).iterator();
537 * Fetches and checks Ensembl's REST version number
541 @SuppressWarnings("unchecked")
542 private void checkEnsemblRestVersion()
544 EnsemblData info = domainData.get(getDomain());
548 Map<String, Object> val = (Map<String, Object>) getJSON(
549 new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON), null,
555 String version = val.get("release").toString();
556 String majorVersion = version.substring(0, version.indexOf("."));
557 String expected = info.expectedRestVersion;
558 String expectedMajorVersion = expected.substring(0,
559 expected.indexOf("."));
560 info.restMajorVersionMismatch = false;
564 * if actual REST major version is ahead of what we expect,
565 * record this in case we want to warn the user
567 if (Float.valueOf(majorVersion) > Float
568 .valueOf(expectedMajorVersion))
570 info.restMajorVersionMismatch = true;
572 } catch (NumberFormatException e)
575 .errPrintln("Error in REST version: " + e.toString());
579 * check if REST version is later than what Jalview has tested against,
580 * if so warn; we don't worry if it is earlier (this indicates Jalview has
581 * been tested in advance against the next pending REST version)
583 boolean laterVersion = StringUtils.compareVersions(version,
587 jalview.bin.Console.errPrintln(String.format(
588 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
589 getDbSource(), expected, version, REST_CHANGE_LOG));
591 info.restVersion = version;
592 } catch (Throwable t)
594 jalview.bin.Console.errPrintln(
595 "Error checking Ensembl REST version: " + t.getMessage());
599 public boolean isRestMajorVersionMismatch()
601 return domainData.get(getDomain()).restMajorVersionMismatch;
605 * Fetches and checks Ensembl's data version number
609 @SuppressWarnings("unchecked")
610 private void checkEnsemblDataVersion()
612 Map<String, Object> val;
615 val = (Map<String, Object>) getJSON(
616 new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON), null,
622 List<Object> versions = (List<Object>) val.get("releases");
623 domainData.get(getDomain()).dataVersion = versions.get(0).toString();
624 } catch (Throwable e)
625 {// could be IOException | ParseException e) {
626 jalview.bin.Console.errPrintln(
627 "Error checking Ensembl data version: " + e.getMessage());
631 public String getEnsemblDataVersion()
633 return domainData.get(getDomain()).dataVersion;
637 public String getDbVersion()
639 return getEnsemblDataVersion();