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.bin.Cache;
24 import jalview.bin.Jalview;
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
55 Cache.addJ2SDirectDatabaseCall("http://rest.ensembl");
56 Cache.addJ2SDirectDatabaseCall("https://rest.ensembl");
59 private static final int DEFAULT_READ_TIMEOUT = 5 * 60 * 1000; // 5 minutes
61 private static final int CONNECT_TIMEOUT_MS = 10 * 1000; // 10 seconds
63 private static final int MAX_RETRIES = 3;
65 private static final int HTTP_OK = 200;
67 private static final int HTTP_OVERLOAD = 429;
70 * update these constants when Jalview has been checked / updated for
71 * changes to Ensembl REST API (ref JAL-2105)
72 * @see https://github.com/Ensembl/ensembl-rest/wiki/Change-log
73 * @see http://rest.ensembl.org/info/rest?content-type=application/json
75 private static final String LATEST_ENSEMBLGENOMES_REST_VERSION = "7.0";
77 private static final String LATEST_ENSEMBL_REST_VERSION = "7.0";
79 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
81 private static Map<String, EnsemblData> domainData;
83 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
85 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
87 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
91 domainData = new HashMap<>();
92 domainData.put(DEFAULT_ENSEMBL_BASEURL,
93 new EnsemblData(DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
94 domainData.put(DEFAULT_ENSEMBL_GENOMES_BASEURL, new EnsemblData(
95 DEFAULT_ENSEMBL_GENOMES_BASEURL, LATEST_ENSEMBLGENOMES_REST_VERSION));
98 protected volatile boolean inProgress = false;
101 * Default constructor to use rest.ensembl.org
103 public EnsemblRestClient()
108 * initialise domain info lazily
110 if (!domainData.containsKey(ensemblDomain))
112 domainData.put(ensemblDomain,
113 new EnsemblData(ensemblDomain, LATEST_ENSEMBL_REST_VERSION));
115 if (!domainData.containsKey(ensemblGenomesDomain))
117 domainData.put(ensemblGenomesDomain, new EnsemblData(
118 ensemblGenomesDomain, LATEST_ENSEMBLGENOMES_REST_VERSION));
123 * Constructor given the target domain to fetch data from
127 public EnsemblRestClient(String d)
133 public boolean queryInProgress()
139 public StringBuffer getRawRecords()
145 * Returns the URL for the client http request
149 * @throws MalformedURLException
151 protected abstract URL getUrl(List<String> ids)
152 throws MalformedURLException;
155 * Returns true if client uses GET method, false if it uses POST
159 protected abstract boolean useGetRequest();
162 * Returns the desired value for the Content-Type request header. Default is
163 * application/json, override if required to vary this.
166 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
168 protected String getRequestMimeType()
170 return "application/json";
174 * Return the desired value for the Accept request header. Default is
175 * application/json, override if required to vary this.
178 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
180 protected String getResponseMimeType()
182 return "application/json";
186 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
187 * indicates available, else false
189 * @see http://rest.ensembl.org/documentation/info/ping
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)
200 URL ping = new URL(pingUrl);
203 * expect {"ping":1} if ok
204 * if ping takes more than 2 seconds to respond, treat as if unavailable
206 br = getHttpResponse(ping, null, 2 * 1000);
209 // error reponse status
212 JSONParser jp = new JSONParser();
213 JSONObject val = (JSONObject) jp.parse(br);
214 String pingString = val.get("ping").toString();
215 return pingString != null;
216 } catch (Throwable t)
219 "Error connecting to " + pingUrl + ": " + t.getMessage());
227 } catch (IOException e)
237 * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
238 * If the request failed the return value may be null.
242 * @throws IOException
244 protected BufferedReader getSequenceReader(List<String> ids)
247 URL url = getUrl(ids);
249 BufferedReader reader = getHttpResponse(url, ids);
254 * Gets a reader to the HTTP response, using the default read timeout of 5
260 * @throws IOException
262 protected BufferedReader getHttpResponse(URL url, List<String> ids)
265 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
269 * Sends the HTTP request and gets the response as a reader. Returns null if
270 * the HTTP response code was not 200.
274 * written as Json POST body if more than one
278 * @throws IOException
280 protected BufferedReader getHttpResponse(URL url, List<String> ids,
281 int readTimeout) throws IOException
283 int retriesLeft = MAX_RETRIES;
284 HttpURLConnection connection = null;
285 int responseCode = 0;
287 while (retriesLeft > 0)
289 connection = tryConnection(url, ids, readTimeout);
290 responseCode = connection.getResponseCode();
291 if (responseCode == HTTP_OVERLOAD) // 429
294 checkRetryAfter(connection);
301 if (responseCode != HTTP_OK) // 200
304 * note: a GET request for an invalid id returns an error code e.g. 415
305 * but POST request returns 200 and an empty Fasta response
307 System.err.println("Response code " + responseCode + " for " + url);
311 InputStream response = connection.getInputStream();
313 // System.out.println(getClass().getName() + " took "
314 // + (System.currentTimeMillis() - now) + "ms to fetch");
316 BufferedReader reader = null;
317 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
326 * @throws IOException
327 * @throws ProtocolException
329 protected HttpURLConnection tryConnection(URL url, List<String> ids,
330 int readTimeout) throws IOException, ProtocolException
332 // System.out.println(System.currentTimeMillis() + " " + url);
333 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
336 * POST method allows multiple queries in one request; it is supported for
337 * sequence queries, but not for overlap
339 boolean multipleIds = ids != null && ids.size() > 1;
340 connection.setRequestMethod(
341 multipleIds ? HttpMethod.POST : HttpMethod.GET);
342 connection.setRequestProperty("Content-Type", getRequestMimeType());
343 connection.setRequestProperty("Accept", getResponseMimeType());
345 connection.setDoInput(true);
346 connection.setDoOutput(multipleIds);
348 connection.setUseCaches(false);
349 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
350 connection.setReadTimeout(readTimeout);
354 writePostBody(connection, ids);
360 * Inspects response headers for a 'retry-after' directive, and waits for the
361 * directed period (if less than 10 seconds)
363 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
366 void checkRetryAfter(HttpURLConnection connection)
368 String retryDelay = connection.getHeaderField("Retry-After");
373 if (retryDelay != null)
377 int retrySecs = Integer.valueOf(retryDelay);
378 if (retrySecs > 0 && retrySecs < 10)
381 .println("Ensembl REST service rate limit exceeded, waiting "
382 + retryDelay + " seconds before retrying");
383 Thread.sleep(1000 * retrySecs);
385 } catch (NumberFormatException | InterruptedException e)
387 System.err.println("Error handling Retry-After: " + e.getMessage());
393 * Rechecks if Ensembl is responding, unless the last check was successful and
394 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
395 * else false. Also retrieves and saves the current version of Ensembl data
396 * and REST services at intervals.
400 protected boolean isEnsemblAvailable()
402 EnsemblData info = domainData.get(getDomain());
404 long now = System.currentTimeMillis();
407 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
409 boolean retestAvailability = (now
410 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
411 if (!info.restAvailable || retestAvailability)
413 info.restAvailable = checkEnsembl();
414 info.lastAvailableCheckTime = now;
418 * refetch Ensembl versions if the recheck period has elapsed
420 boolean refetchVersion = (now
421 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
424 checkEnsemblRestVersion();
425 checkEnsemblDataVersion();
426 info.lastVersionCheckTime = now;
429 return info.restAvailable;
433 * Constructs, writes and flushes the POST body of the request, containing the
434 * query ids in JSON format
438 * @throws IOException
440 protected void writePostBody(HttpURLConnection connection,
441 List<String> ids) throws IOException
444 StringBuilder postBody = new StringBuilder(64);
445 postBody.append("{\"ids\":[");
447 for (String id : ids)
451 postBody.append(",");
454 postBody.append("\"");
455 postBody.append(id.trim());
456 postBody.append("\"");
458 postBody.append("]}");
459 byte[] thepostbody = postBody.toString().getBytes();
460 connection.setRequestProperty("Content-Length",
461 Integer.toString(thepostbody.length));
462 DataOutputStream wr = new DataOutputStream(
463 connection.getOutputStream());
464 wr.write(thepostbody);
470 * Fetches and checks Ensembl's REST version number
474 private void checkEnsemblRestVersion()
476 EnsemblData info = domainData.get(getDomain());
478 JSONParser jp = new JSONParser();
482 url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON);
483 BufferedReader br = getHttpResponse(url, null);
488 JSONObject val = (JSONObject) jp.parse(br);
489 String version = val.get("release").toString();
490 String majorVersion = version.substring(0, version.indexOf("."));
491 String expected = info.expectedRestVersion;
492 String expectedMajorVersion = expected.substring(0,
493 expected.indexOf("."));
494 info.restMajorVersionMismatch = false;
498 * if actual REST major version is ahead of what we expect,
499 * record this in case we want to warn the user
501 if (Float.valueOf(majorVersion) > Float
502 .valueOf(expectedMajorVersion))
504 info.restMajorVersionMismatch = true;
506 } catch (NumberFormatException e)
508 System.err.println("Error in REST version: " + e.toString());
512 * check if REST version is later than what Jalview has tested against,
513 * if so warn; we don't worry if it is earlier (this indicates Jalview has
514 * been tested in advance against the next pending REST version)
516 boolean laterVersion = StringUtils.compareVersions(version,
520 System.err.println(String.format(
521 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
522 getDbSource(), expected, version, REST_CHANGE_LOG));
524 info.restVersion = version;
525 } catch (Throwable t)
528 "Error checking Ensembl REST version: " + t.getMessage());
532 public boolean isRestMajorVersionMismatch()
534 return domainData.get(getDomain()).restMajorVersionMismatch;
538 * Fetches and checks Ensembl's data version number
542 private void checkEnsemblDataVersion()
544 JSONParser jp = new JSONParser();
546 BufferedReader br = null;
550 url = new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
551 br = getHttpResponse(url, null);
554 JSONObject val = (JSONObject) jp.parse(br);
555 JSONArray versions = (JSONArray) val.get("releases");
556 domainData.get(getDomain()).dataVersion = versions.get(0)
559 } catch (Throwable t)
562 "Error checking Ensembl data version: " + t.getMessage());
570 } catch (IOException e)
578 public String getEnsemblDataVersion()
580 return domainData.get(getDomain()).dataVersion;
584 public String getDbVersion()
586 return getEnsemblDataVersion();