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.util.StringUtils;
25 import java.io.BufferedReader;
26 import java.io.DataOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.net.HttpURLConnection;
31 import java.net.MalformedURLException;
32 import java.net.ProtocolException;
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
55 private static final int MAX_RETRIES = 3;
57 private static final int HTTP_OK = 200;
59 private static final int HTTP_OVERLOAD = 429;
62 * update these constants when Jalview has been checked / updated for
63 * changes to Ensembl REST API, and updated JAL-3018
64 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
65 * @see http://rest.ensembl.org/info/rest?content-type=application/json
67 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "9.0";
69 private static final String LATEST_ENSEMBL_REST_VERSION = "9.0";
71 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
73 private static Map<String, EnsemblData> domainData;
75 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
77 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
79 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
83 domainData = new HashMap<>();
84 domainData.put(DEFAULT_ENSEMBL_BASEURL,
85 new EnsemblData(DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
86 domainData.put(DEFAULT_ENSEMBL_GENOMES_BASEURL, new EnsemblData(
87 DEFAULT_ENSEMBL_GENOMES_BASEURL, LATEST_ENSEMBLGENOMES_REST_VERSION));
90 protected volatile boolean inProgress = false;
93 * Default constructor to use rest.ensembl.org
95 public EnsemblRestClient()
100 * initialise domain info lazily
102 if (!domainData.containsKey(ensemblDomain))
104 domainData.put(ensemblDomain,
105 new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
107 if (!domainData.containsKey(ensemblGenomesDomain))
109 domainData.put(ensemblGenomesDomain, new EnsemblData(
110 ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
115 * Constructor given the target domain to fetch data from
119 public EnsemblRestClient(String d)
125 public boolean queryInProgress()
131 public StringBuffer getRawRecords()
137 * Returns the URL for the client http request
141 * @throws MalformedURLException
143 protected abstract URL getUrl(List<String> ids)
144 throws MalformedURLException;
147 * Returns true if client uses GET method, false if it uses POST
151 protected abstract boolean useGetRequest();
154 * Returns the desired value for the Content-Type request header. Default is
155 * application/json, override if required to vary this.
158 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
160 protected String getRequestMimeType()
162 return "application/json";
166 * Return the desired value for the Accept request header. Default is
167 * application/json, override if required to vary this.
170 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
172 protected String getResponseMimeType()
174 return "application/json";
178 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
179 * indicates available, else false
181 * @see http://rest.ensembl.org/documentation/info/ping
184 boolean checkEnsembl()
186 BufferedReader br = null;
187 String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
190 // note this format works for both ensembl and ensemblgenomes
191 // info/ping.json works for ensembl only (March 2016)
192 URL ping = new URL(pingUrl);
195 * expect {"ping":1} if ok
196 * if ping takes more than 2 seconds to respond, treat as if unavailable
198 br = getHttpResponse(ping, null, 2 * 1000);
201 // error reponse status
204 JSONParser jp = new JSONParser();
205 JSONObject val = (JSONObject) jp.parse(br);
206 String pingString = val.get("ping").toString();
207 return pingString != null;
208 } catch (Throwable t)
211 "Error connecting to " + pingUrl + ": " + t.getMessage());
219 } catch (IOException e)
229 * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
230 * If the request failed the return value may be null.
234 * @throws IOException
236 protected BufferedReader getSequenceReader(List<String> ids)
239 URL url = getUrl(ids);
241 BufferedReader reader = getHttpResponse(url, ids);
246 * Gets a reader to the HTTP response, using the default read timeout of 5
252 * @throws IOException
254 protected BufferedReader getHttpResponse(URL url, List<String> ids)
257 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
261 * Sends the HTTP request and gets the response as a reader. Returns null if
262 * the HTTP response code was not 200.
266 * written as Json POST body if more than one
270 * @throws IOException
272 protected BufferedReader getHttpResponse(URL url, List<String> ids,
273 int readTimeout) throws IOException
275 int retriesLeft = MAX_RETRIES;
276 HttpURLConnection connection = null;
277 int responseCode = 0;
279 while (retriesLeft > 0)
281 connection = tryConnection(url, ids, readTimeout);
282 responseCode = connection.getResponseCode();
283 if (responseCode == HTTP_OVERLOAD) // 429
286 checkRetryAfter(connection);
293 if (responseCode != HTTP_OK) // 200
296 * note: a GET request for an invalid id returns an error code e.g. 415
297 * but POST request returns 200 and an empty Fasta response
299 System.err.println("Response code " + responseCode + " for " + url);
303 InputStream response = connection.getInputStream();
305 // System.out.println(getClass().getName() + " took "
306 // + (System.currentTimeMillis() - now) + "ms to fetch");
308 BufferedReader reader = null;
309 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
318 * @throws IOException
319 * @throws ProtocolException
321 protected HttpURLConnection tryConnection(URL url, List<String> ids,
322 int readTimeout) throws IOException, ProtocolException
324 // System.out.println(System.currentTimeMillis() + " " + url);
325 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
328 * POST method allows multiple queries in one request; it is supported for
329 * sequence queries, but not for overlap
331 boolean multipleIds = ids != null && ids.size() > 1;
332 connection.setRequestMethod(
333 multipleIds ? HttpMethod.POST : HttpMethod.GET);
334 connection.setRequestProperty("Content-Type", getRequestMimeType());
335 connection.setRequestProperty("Accept", getResponseMimeType());
337 connection.setUseCaches(false);
338 connection.setDoInput(true);
339 connection.setDoOutput(multipleIds);
341 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
342 connection.setReadTimeout(readTimeout);
346 writePostBody(connection, ids);
352 * Inspects response headers for a 'retry-after' directive, and waits for the
353 * directed period (if less than 10 seconds)
355 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
358 void checkRetryAfter(HttpURLConnection connection)
360 String retryDelay = connection.getHeaderField("Retry-After");
365 if (retryDelay != null)
369 int retrySecs = Integer.valueOf(retryDelay);
370 if (retrySecs > 0 && retrySecs < 10)
373 .println("Ensembl REST service rate limit exceeded, waiting "
374 + retryDelay + " seconds before retrying");
375 Thread.sleep(1000 * retrySecs);
377 } catch (NumberFormatException | InterruptedException e)
379 System.err.println("Error handling Retry-After: " + e.getMessage());
385 * Rechecks if Ensembl is responding, unless the last check was successful and
386 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
387 * else false. Also retrieves and saves the current version of Ensembl data
388 * and REST services at intervals.
392 protected boolean isEnsemblAvailable()
394 EnsemblData info = domainData.get(getDomain());
396 long now = System.currentTimeMillis();
399 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
401 boolean retestAvailability = (now
402 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
403 if (!info.restAvailable || retestAvailability)
405 info.restAvailable = checkEnsembl();
406 info.lastAvailableCheckTime = now;
410 * refetch Ensembl versions if the recheck period has elapsed
412 boolean refetchVersion = (now
413 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
416 checkEnsemblRestVersion();
417 checkEnsemblDataVersion();
418 info.lastVersionCheckTime = now;
421 return info.restAvailable;
425 * Constructs, writes and flushes the POST body of the request, containing the
426 * query ids in JSON format
430 * @throws IOException
432 protected void writePostBody(HttpURLConnection connection,
433 List<String> ids) throws IOException
436 StringBuilder postBody = new StringBuilder(64);
437 postBody.append("{\"ids\":[");
439 for (String id : ids)
443 postBody.append(",");
446 postBody.append("\"");
447 postBody.append(id.trim());
448 postBody.append("\"");
450 postBody.append("]}");
451 byte[] thepostbody = postBody.toString().getBytes();
452 connection.setRequestProperty("Content-Length",
453 Integer.toString(thepostbody.length));
454 DataOutputStream wr = new DataOutputStream(
455 connection.getOutputStream());
456 wr.write(thepostbody);
462 * Fetches and checks Ensembl's REST version number
466 private void checkEnsemblRestVersion()
468 EnsemblData info = domainData.get(getDomain());
470 JSONParser jp = new JSONParser();
474 url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON);
475 BufferedReader br = getHttpResponse(url, null);
480 JSONObject val = (JSONObject) jp.parse(br);
481 String version = val.get("release").toString();
482 String majorVersion = version.substring(0, version.indexOf("."));
483 String expected = info.expectedRestVersion;
484 String expectedMajorVersion = expected.substring(0,
485 expected.indexOf("."));
486 info.restMajorVersionMismatch = false;
490 * if actual REST major version is ahead of what we expect,
491 * record this in case we want to warn the user
493 if (Float.valueOf(majorVersion) > Float
494 .valueOf(expectedMajorVersion))
496 info.restMajorVersionMismatch = true;
498 } catch (NumberFormatException e)
500 System.err.println("Error in REST version: " + e.toString());
504 * check if REST version is later than what Jalview has tested against,
505 * if so warn; we don't worry if it is earlier (this indicates Jalview has
506 * been tested in advance against the next pending REST version)
508 boolean laterVersion = StringUtils.compareVersions(version,
512 System.err.println(String.format(
513 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
514 getDbSource(), expected, version, REST_CHANGE_LOG));
516 info.restVersion = version;
517 } catch (Throwable t)
520 "Error checking Ensembl REST version: " + t.getMessage());
524 public boolean isRestMajorVersionMismatch()
526 return domainData.get(getDomain()).restMajorVersionMismatch;
530 * Fetches and checks Ensembl's data version number
534 private void checkEnsemblDataVersion()
536 JSONParser jp = new JSONParser();
538 BufferedReader br = null;
542 url = new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
543 br = getHttpResponse(url, null);
546 JSONObject val = (JSONObject) jp.parse(br);
547 JSONArray versions = (JSONArray) val.get("releases");
548 domainData.get(getDomain()).dataVersion = versions.get(0)
551 } catch (Throwable t)
554 "Error checking Ensembl data version: " + t.getMessage());
562 } catch (IOException e)
570 public String getEnsemblDataVersion()
572 return domainData.get(getDomain()).dataVersion;
576 public String getDbVersion()
578 return getEnsemblDataVersion();