package jalview.ext.ensembl; import jalview.datamodel.AlignmentI; import java.io.BufferedReader; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class EnsemblInfo extends EnsemblRestClient { /* * cached upper-cased results of REST /info/divisions service, * currently (from April 2019) * { "ENSEMBLFUNGI", "http://rest.ensembl.org", * "ENSEMBLBACTERIA", "http://rest.ensembl.org", * "ENSEMBLPROTISTS", "http://rest.ensembl.org", * "ENSEMBLMETAZOA", "http://rest.ensembl.org", * "ENSEMBLPLANTS", "http://rest.ensembl.org", * "ENSEMBL", "http://rest.ensembl.org" } * } */ private static Map divisions; /** * Constructor */ public EnsemblInfo() { super(); } @Override public String getDbName() { return "ENSEMBL"; } @Override public AlignmentI getSequenceRecords(String queries) throws Exception { return null; } @Override protected URL getUrl(List ids) throws MalformedURLException { return null; } @Override protected boolean useGetRequest() { return true; } /** * Answers the domain (e.g. http://rest.ensembl.org) for the given division, * or null if not recognised by Ensembl * * @param division * @return */ public String getDomain(String division) { if (divisions == null) { fetchDivisions(); } return divisions.get(division.toUpperCase()); } /** * On first request only, populate the lookup map by fetching the list of * divisions known to Ensembl */ void fetchDivisions() { divisions = new HashMap<>(); BufferedReader br = null; try { URL url = getDivisionsUrl(); if (url != null) { br = getHttpResponse(url, null); } parseResponse(br); } catch (IOException e) { // ignore } finally { if (br != null) { try { br.close(); } catch (IOException e) { // ignore } } } } /** * Parses the JSON response to /info/divisions, and add each to the lookup map * * @param br */ void parseResponse(BufferedReader br) { JSONParser jp = new JSONParser(); try { JSONArray parsed = (JSONArray) jp.parse(br); String domain = getDomain(); Iterator rvals = parsed.iterator(); while (rvals.hasNext()) { String division = rvals.next().toString(); divisions.put(division.toUpperCase(), domain); } } catch (IOException | ParseException | NumberFormatException e) { // ignore } } /** * Constructs the URL for the Ensembl /info/divisions REST service * * @return * @throws MalformedURLException */ URL getDivisionsUrl() throws MalformedURLException { return new URL( getDomain() + "/info/divisions?content-type=application/json"); } /** * Returns the set of 'divisions' recognised by Ensembl * * @return */ public Set getDivisions() { if (divisions == null) { fetchDivisions(); } return divisions.keySet(); } }