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.DataSourceType;
24 import jalview.io.FileParse;
25 import jalview.util.StringUtils;
27 import java.io.BufferedReader;
28 import java.io.DataOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.net.HttpURLConnection;
33 import java.net.MalformedURLException;
34 import java.net.ProtocolException;
36 import java.util.HashMap;
37 import java.util.List;
40 import javax.ws.rs.HttpMethod;
42 import org.json.simple.JSONArray;
43 import org.json.simple.JSONObject;
44 import org.json.simple.parser.JSONParser;
47 * Base class for Ensembl REST service clients
51 abstract class EnsemblRestClient extends EnsemblSequenceFetcher
53 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
55 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
57 private static final int MAX_RETRIES = 3;
59 private static final int HTTP_OK = 200;
61 private static final int HTTP_OVERLOAD = 429;
64 * update these constants when Jalview has been checked / updated for
65 * changes to Ensembl REST API (ref JAL-2105)
66 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
67 * @see http://rest.ensembl.org/info/rest?content-type=application/json
69 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "6.0";
71 private static final String LATEST_ENSEMBL_REST_VERSION = "6.1";
73 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
75 private static Map<String, EnsemblInfo> domainData;
77 // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
78 private static final String PING_URL = "http://rest.ensembl.org/info/ping.json";
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(ENSEMBL_REST,
90 new EnsemblInfo(ENSEMBL_REST, LATEST_ENSEMBL_REST_VERSION));
91 domainData.put(ENSEMBL_GENOMES_REST, new EnsemblInfo(
92 ENSEMBL_GENOMES_REST, LATEST_ENSEMBLGENOMES_REST_VERSION));
95 protected volatile boolean inProgress = false;
98 * Default constructor to use rest.ensembl.org
100 public EnsemblRestClient()
106 * Constructor given the target domain to fetch data from
110 public EnsemblRestClient(String d)
116 public boolean queryInProgress()
122 public StringBuffer getRawRecords()
128 * Returns the URL for the client http request
132 * @throws MalformedURLException
134 protected abstract URL getUrl(List<String> ids)
135 throws MalformedURLException;
138 * Returns true if client uses GET method, false if it uses POST
142 protected abstract boolean useGetRequest();
145 * Return the desired value for the Content-Type request header
150 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
152 protected abstract String getRequestMimeType(boolean multipleIds);
155 * Return the desired value for the Accept request header
158 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
160 protected abstract String getResponseMimeType();
163 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
164 * indicates available, else false
166 * @see http://rest.ensembl.org/documentation/info/ping
169 boolean checkEnsembl()
171 BufferedReader br = null;
174 // note this format works for both ensembl and ensemblgenomes
175 // info/ping.json works for ensembl only (March 2016)
176 URL ping = new URL(getDomain() + "/info/ping" + CONTENT_TYPE_JSON);
179 * expect {"ping":1} if ok
180 * if ping takes more than 2 seconds to respond, treat as if unavailable
182 br = getHttpResponse(ping, null, 2 * 1000);
185 // error reponse status
188 JSONParser jp = new JSONParser();
189 JSONObject val = (JSONObject) jp.parse(br);
190 String pingString = val.get("ping").toString();
191 return pingString != null;
192 } catch (Throwable t)
195 "Error connecting to " + PING_URL + ": " + t.getMessage());
203 } catch (IOException e)
213 * returns a reader to a Fasta response from the Ensembl sequence endpoint
217 * @throws IOException
219 protected FileParse getSequenceReader(List<String> ids) throws IOException
221 URL url = getUrl(ids);
223 BufferedReader reader = getHttpResponse(url, ids);
229 FileParse fp = new FileParse(reader, url.toString(),
235 * Gets a reader to the HTTP response, using the default read timeout of 5
241 * @throws IOException
243 protected BufferedReader getHttpResponse(URL url, List<String> ids)
246 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
250 * Sends the HTTP request and gets the response as a reader
254 * written as Json POST body if more than one
258 * @throws IOException
259 * if response code was not 200, or other I/O error
261 protected BufferedReader getHttpResponse(URL url, List<String> ids,
262 int readTimeout) throws IOException
264 int retriesLeft = MAX_RETRIES;
265 HttpURLConnection connection = null;
266 int responseCode = 0;
268 while (retriesLeft > 0)
270 connection = tryConnection(url, ids, readTimeout);
271 responseCode = connection.getResponseCode();
272 if (responseCode == HTTP_OVERLOAD) // 429
275 checkRetryAfter(connection);
282 if (responseCode != HTTP_OK) // 200
285 * note: a GET request for an invalid id returns an error code e.g. 415
286 * but POST request returns 200 and an empty Fasta response
288 System.err.println("Response code " + responseCode + " for " + url);
292 InputStream response = connection.getInputStream();
294 // System.out.println(getClass().getName() + " took "
295 // + (System.currentTimeMillis() - now) + "ms to fetch");
297 BufferedReader reader = null;
298 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
307 * @throws IOException
308 * @throws ProtocolException
310 protected HttpURLConnection tryConnection(URL url, List<String> ids,
311 int readTimeout) throws IOException, ProtocolException
313 // System.out.println(System.currentTimeMillis() + " " + url);
314 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
317 * POST method allows multiple queries in one request; it is supported for
318 * sequence queries, but not for overlap
320 boolean multipleIds = ids != null && ids.size() > 1;
321 connection.setRequestMethod(
322 multipleIds ? HttpMethod.POST : HttpMethod.GET);
323 connection.setRequestProperty("Content-Type",
324 getRequestMimeType(multipleIds));
325 connection.setRequestProperty("Accept", getResponseMimeType());
327 connection.setUseCaches(false);
328 connection.setDoInput(true);
329 connection.setDoOutput(multipleIds);
331 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
332 connection.setReadTimeout(readTimeout);
336 writePostBody(connection, ids);
342 * Inspects response headers for a 'retry-after' directive, and waits for the
343 * directed period (if less than 10 seconds)
345 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
348 void checkRetryAfter(HttpURLConnection connection)
350 String retryDelay = connection.getHeaderField("Retry-After");
355 if (retryDelay != null)
359 int retrySecs = Integer.valueOf(retryDelay);
360 if (retrySecs > 0 && retrySecs < 10)
363 .println("Ensembl REST service rate limit exceeded, waiting "
364 + retryDelay + " seconds before retrying");
365 Thread.sleep(1000 * retrySecs);
367 } catch (NumberFormatException | InterruptedException e)
369 System.err.println("Error handling Retry-After: " + e.getMessage());
375 * Rechecks if Ensembl is responding, unless the last check was successful and
376 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
377 * else false. Also retrieves and saves the current version of Ensembl data
378 * and REST services at intervals.
382 protected boolean isEnsemblAvailable()
384 EnsemblInfo info = domainData.get(getDomain());
386 long now = System.currentTimeMillis();
389 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
391 boolean retestAvailability = (now
392 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
393 if (!info.restAvailable || retestAvailability)
395 info.restAvailable = checkEnsembl();
396 info.lastAvailableCheckTime = now;
400 * refetch Ensembl versions if the recheck period has elapsed
402 boolean refetchVersion = (now
403 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
406 checkEnsemblRestVersion();
407 checkEnsemblDataVersion();
408 info.lastVersionCheckTime = now;
411 return info.restAvailable;
415 * Constructs, writes and flushes the POST body of the request, containing the
416 * query ids in JSON format
420 * @throws IOException
422 protected void writePostBody(HttpURLConnection connection,
423 List<String> ids) throws IOException
426 StringBuilder postBody = new StringBuilder(64);
427 postBody.append("{\"ids\":[");
429 for (String id : ids)
433 postBody.append(",");
436 postBody.append("\"");
437 postBody.append(id.trim());
438 postBody.append("\"");
440 postBody.append("]}");
441 byte[] thepostbody = postBody.toString().getBytes();
442 connection.setRequestProperty("Content-Length",
443 Integer.toString(thepostbody.length));
444 DataOutputStream wr = new DataOutputStream(
445 connection.getOutputStream());
446 wr.write(thepostbody);
452 * Fetches and checks Ensembl's REST version number
456 private void checkEnsemblRestVersion()
458 EnsemblInfo info = domainData.get(getDomain());
460 JSONParser jp = new JSONParser();
464 url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON);
465 BufferedReader br = getHttpResponse(url, null);
470 JSONObject val = (JSONObject) jp.parse(br);
471 String version = val.get("release").toString();
472 String majorVersion = version.substring(0, version.indexOf("."));
473 String expected = info.expectedRestVersion;
474 String expectedMajorVersion = expected.substring(0,
475 expected.indexOf("."));
476 info.restMajorVersionMismatch = false;
480 * if actual REST major version is ahead of what we expect,
481 * record this in case we want to warn the user
483 if (Float.valueOf(majorVersion) > Float
484 .valueOf(expectedMajorVersion))
486 info.restMajorVersionMismatch = true;
488 } catch (NumberFormatException e)
490 System.err.println("Error in REST version: " + e.toString());
494 * check if REST version is later than what Jalview has tested against,
495 * if so warn; we don't worry if it is earlier (this indicates Jalview has
496 * been tested in advance against the next pending REST version)
498 boolean laterVersion = StringUtils.compareVersions(version,
502 System.err.println(String.format(
503 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
504 getDbSource(), expected, version, REST_CHANGE_LOG));
506 info.restVersion = version;
507 } catch (Throwable t)
510 "Error checking Ensembl REST version: " + t.getMessage());
514 public boolean isRestMajorVersionMismatch()
516 return domainData.get(getDomain()).restMajorVersionMismatch;
520 * Fetches and checks Ensembl's data version number
524 private void checkEnsemblDataVersion()
526 JSONParser jp = new JSONParser();
528 BufferedReader br = null;
532 url = new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
533 br = getHttpResponse(url, null);
536 JSONObject val = (JSONObject) jp.parse(br);
537 JSONArray versions = (JSONArray) val.get("releases");
538 domainData.get(getDomain()).dataVersion = versions.get(0)
541 } catch (Throwable t)
544 "Error checking Ensembl data version: " + t.getMessage());
552 } catch (IOException e)
560 public String getEnsemblDataVersion()
562 return domainData.get(getDomain()).dataVersion;
566 public String getDbVersion()
568 return getEnsemblDataVersion();