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_ENSEMBL_REST_VERSION = "10.0";
69 private static final String REST_CHANGE_LOG = "https://github.com/Ensembl/ensembl-rest/wiki/Change-log";
71 private static Map<String, EnsemblData> domainData;
73 private final static long AVAILABILITY_RETEST_INTERVAL = 10000L; // 10 seconds
75 private final static long VERSION_RETEST_INTERVAL = 1000L * 3600; // 1 hr
77 protected static final String CONTENT_TYPE_JSON = "?content-type=application/json";
81 domainData = new HashMap<>();
82 domainData.put(DEFAULT_ENSEMBL_BASEURL,
83 new EnsemblData(DEFAULT_ENSEMBL_BASEURL, LATEST_ENSEMBL_REST_VERSION));
86 protected volatile boolean inProgress = false;
89 * Default constructor to use rest.ensembl.org
91 public EnsemblRestClient()
96 * initialise domain info lazily
98 String domain = getDomain();
99 if (!domainData.containsKey(domain))
101 domainData.put(domain,
102 new EnsemblData(domain, LATEST_ENSEMBL_REST_VERSION));
107 public boolean queryInProgress()
113 public StringBuffer getRawRecords()
119 * Returns the URL for the client http request
123 * @throws MalformedURLException
125 protected abstract URL getUrl(List<String> ids)
126 throws MalformedURLException;
129 * Returns true if client uses GET method, false if it uses POST
133 protected abstract boolean useGetRequest();
136 * Returns the desired value for the Content-Type request header. Default is
137 * application/json, override if required to vary this.
140 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
142 protected String getRequestMimeType()
144 return "application/json";
148 * Return the desired value for the Accept request header. Default is
149 * application/json, override if required to vary this.
152 * @see https://github.com/Ensembl/ensembl-rest/wiki/HTTP-Headers
154 protected String getResponseMimeType()
156 return "application/json";
160 * Checks Ensembl's REST 'ping' endpoint, and returns true if response
161 * indicates available, else false
163 * @see http://rest.ensembl.org/documentation/info/ping
166 boolean checkEnsembl()
168 BufferedReader br = null;
169 String pingUrl = getDomain() + "/info/ping" + CONTENT_TYPE_JSON;
172 URL ping = new URL(pingUrl);
175 * expect {"ping":1} if ok
176 * if ping takes more than 2 seconds to respond, treat as if unavailable
178 br = getHttpResponse(ping, null, 2 * 1000);
181 // error reponse status
184 JSONParser jp = new JSONParser();
185 JSONObject val = (JSONObject) jp.parse(br);
186 String pingString = val.get("ping").toString();
187 return pingString != null;
188 } catch (Throwable t)
191 "Error connecting to " + pingUrl + ": " + t.getMessage());
199 } catch (IOException e)
209 * Returns a reader to a (Json) response from the Ensembl sequence endpoint.
210 * If the request failed the return value may be null.
214 * @throws IOException
216 protected BufferedReader getSequenceReader(List<String> ids)
219 URL url = getUrl(ids);
221 BufferedReader reader = getHttpResponse(url, ids);
226 * Gets a reader to the HTTP response, using the default read timeout of 5
232 * @throws IOException
234 protected BufferedReader getHttpResponse(URL url, List<String> ids)
237 return getHttpResponse(url, ids, DEFAULT_READ_TIMEOUT);
241 * Sends the HTTP request and gets the response as a reader. Returns null if
242 * the HTTP response code was not 200.
246 * written as Json POST body if more than one
250 * @throws IOException
252 protected BufferedReader getHttpResponse(URL url, List<String> ids,
253 int readTimeout) throws IOException
255 int retriesLeft = MAX_RETRIES;
256 HttpURLConnection connection = null;
257 int responseCode = 0;
259 while (retriesLeft > 0)
261 connection = tryConnection(url, ids, readTimeout);
262 responseCode = connection.getResponseCode();
263 if (responseCode == HTTP_OVERLOAD) // 429
266 checkRetryAfter(connection);
273 if (responseCode != HTTP_OK) // 200
276 * note: a GET request for an invalid id returns an error code e.g. 415
277 * but POST request returns 200 and an empty Fasta response
279 System.err.println("Response code " + responseCode + " for " + url);
283 InputStream response = connection.getInputStream();
285 // System.out.println(getClass().getName() + " took "
286 // + (System.currentTimeMillis() - now) + "ms to fetch");
288 BufferedReader reader = null;
289 reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
298 * @throws IOException
299 * @throws ProtocolException
301 protected HttpURLConnection tryConnection(URL url, List<String> ids,
302 int readTimeout) throws IOException, ProtocolException
304 // System.out.println(System.currentTimeMillis() + " " + url);
305 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
308 * POST method allows multiple queries in one request; it is supported for
309 * sequence queries, but not for overlap
311 boolean multipleIds = ids != null && ids.size() > 1;
312 connection.setRequestMethod(
313 multipleIds ? HttpMethod.POST : HttpMethod.GET);
314 connection.setRequestProperty("Content-Type", getRequestMimeType());
315 connection.setRequestProperty("Accept", getResponseMimeType());
317 connection.setUseCaches(false);
318 connection.setDoInput(true);
319 connection.setDoOutput(multipleIds);
321 connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
322 connection.setReadTimeout(readTimeout);
326 writePostBody(connection, ids);
332 * Inspects response headers for a 'retry-after' directive, and waits for the
333 * directed period (if less than 10 seconds)
335 * @see https://github.com/Ensembl/ensembl-rest/wiki/Rate-Limits
338 void checkRetryAfter(HttpURLConnection connection)
340 String retryDelay = connection.getHeaderField("Retry-After");
345 if (retryDelay != null)
349 int retrySecs = Integer.valueOf(retryDelay);
350 if (retrySecs > 0 && retrySecs < 10)
353 .println("Ensembl REST service rate limit exceeded, waiting "
354 + retryDelay + " seconds before retrying");
355 Thread.sleep(1000 * retrySecs);
357 } catch (NumberFormatException | InterruptedException e)
359 System.err.println("Error handling Retry-After: " + e.getMessage());
365 * Rechecks if Ensembl is responding, unless the last check was successful and
366 * the retest interval has not yet elapsed. Returns true if Ensembl is up,
367 * else false. Also retrieves and saves the current version of Ensembl data
368 * and REST services at intervals.
372 protected boolean isEnsemblAvailable()
374 EnsemblData info = domainData.get(getDomain());
376 long now = System.currentTimeMillis();
379 * recheck if Ensembl is up if it was down, or the recheck period has elapsed
381 boolean retestAvailability = (now
382 - info.lastAvailableCheckTime) > AVAILABILITY_RETEST_INTERVAL;
383 if (!info.restAvailable || retestAvailability)
385 info.restAvailable = checkEnsembl();
386 info.lastAvailableCheckTime = now;
390 * refetch Ensembl versions if the recheck period has elapsed
392 boolean refetchVersion = (now
393 - info.lastVersionCheckTime) > VERSION_RETEST_INTERVAL;
396 checkEnsemblRestVersion();
397 checkEnsemblDataVersion();
398 info.lastVersionCheckTime = now;
401 return info.restAvailable;
405 * Constructs, writes and flushes the POST body of the request, containing the
406 * query ids in JSON format
410 * @throws IOException
412 protected void writePostBody(HttpURLConnection connection,
413 List<String> ids) throws IOException
416 StringBuilder postBody = new StringBuilder(64);
417 postBody.append("{\"ids\":[");
419 for (String id : ids)
423 postBody.append(",");
426 postBody.append("\"");
427 postBody.append(id.trim());
428 postBody.append("\"");
430 postBody.append("]}");
431 byte[] thepostbody = postBody.toString().getBytes();
432 connection.setRequestProperty("Content-Length",
433 Integer.toString(thepostbody.length));
434 DataOutputStream wr = new DataOutputStream(
435 connection.getOutputStream());
436 wr.write(thepostbody);
442 * Fetches and checks Ensembl's REST version number
446 private void checkEnsemblRestVersion()
448 EnsemblData info = domainData.get(getDomain());
450 JSONParser jp = new JSONParser();
454 url = new URL(getDomain() + "/info/rest" + CONTENT_TYPE_JSON);
455 BufferedReader br = getHttpResponse(url, null);
460 JSONObject val = (JSONObject) jp.parse(br);
461 String version = val.get("release").toString();
462 String majorVersion = version.substring(0, version.indexOf("."));
463 String expected = info.expectedRestVersion;
464 String expectedMajorVersion = expected.substring(0,
465 expected.indexOf("."));
466 info.restMajorVersionMismatch = false;
470 * if actual REST major version is ahead of what we expect,
471 * record this in case we want to warn the user
473 if (Float.valueOf(majorVersion) > Float
474 .valueOf(expectedMajorVersion))
476 info.restMajorVersionMismatch = true;
478 } catch (NumberFormatException e)
480 System.err.println("Error in REST version: " + e.toString());
484 * check if REST version is later than what Jalview has tested against,
485 * if so warn; we don't worry if it is earlier (this indicates Jalview has
486 * been tested in advance against the next pending REST version)
488 boolean laterVersion = StringUtils.compareVersions(version,
492 System.err.println(String.format(
493 "EnsemblRestClient expected %s REST version %s but found %s, see %s",
494 getDbSource(), expected, version, REST_CHANGE_LOG));
496 info.restVersion = version;
497 } catch (Throwable t)
500 "Error checking Ensembl REST version: " + t.getMessage());
504 public boolean isRestMajorVersionMismatch()
506 return domainData.get(getDomain()).restMajorVersionMismatch;
510 * Fetches and checks Ensembl's data version number
514 private void checkEnsemblDataVersion()
516 JSONParser jp = new JSONParser();
518 BufferedReader br = null;
522 url = new URL(getDomain() + "/info/data" + CONTENT_TYPE_JSON);
523 br = getHttpResponse(url, null);
526 JSONObject val = (JSONObject) jp.parse(br);
527 JSONArray versions = (JSONArray) val.get("releases");
528 domainData.get(getDomain()).dataVersion = versions.get(0)
531 } catch (Throwable t)
534 "Error checking Ensembl data version: " + t.getMessage());
542 } catch (IOException e)
550 public String getEnsemblDataVersion()
552 return domainData.get(getDomain()).dataVersion;
556 public String getDbVersion()
558 return getEnsemblDataVersion();