JAL-3076 fetch Ensembl sequence as JSON instead of Fasta
[jalview.git] / src / jalview / ext / ensembl / EnsemblXref.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.ext.ensembl;
22
23 import jalview.datamodel.AlignmentI;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.util.DBRefUtils;
26
27 import java.io.BufferedReader;
28 import java.io.IOException;
29 import java.net.MalformedURLException;
30 import java.net.URL;
31 import java.util.ArrayList;
32 import java.util.Iterator;
33 import java.util.List;
34
35 import org.json.simple.JSONArray;
36 import org.json.simple.JSONObject;
37 import org.json.simple.parser.JSONParser;
38 import org.json.simple.parser.ParseException;
39
40 /**
41  * A class to fetch cross-references from Ensembl by calling the /xrefs REST
42  * service
43  * 
44  * @author gmcarstairs
45  * @see http://rest.ensembl.org/documentation/info/xref_id
46  */
47 class EnsemblXref extends EnsemblRestClient
48 {
49
50   private static final String GO_GENE_ONTOLOGY = "GO";
51
52   private String dbName = "ENSEMBL (xref)";
53
54   /**
55    * Constructor given the target domain to fetch data from
56    * 
57    * @param d
58    */
59   public EnsemblXref(String d, String dbSource, String version)
60   {
61     super(d);
62     dbName = dbSource;
63     xrefVersion = dbSource + ":" + version;
64
65   }
66
67   @Override
68   public String getDbName()
69   {
70     return dbName;
71   }
72
73   @Override
74   public AlignmentI getSequenceRecords(String queries) throws Exception
75   {
76     return null;
77   }
78
79   @Override
80   protected URL getUrl(List<String> ids) throws MalformedURLException
81   {
82     return getUrl(ids.get(0));
83   }
84
85   @Override
86   protected boolean useGetRequest()
87   {
88     return true;
89   }
90
91   /**
92    * Calls the Ensembl xrefs REST endpoint and retrieves any cross-references
93    * ("primary_id") for the given identifier (Ensembl accession id) and database
94    * names. The "dbname" returned by Ensembl is canonicalised to Jalview's
95    * standard version, and a DBRefEntry constructed. Currently takes all
96    * identifiers apart from GO terms and synonyms.
97    * 
98    * @param identifier
99    *          an Ensembl stable identifier
100    * @return
101    */
102   public List<DBRefEntry> getCrossReferences(String identifier)
103   {
104     List<DBRefEntry> result = new ArrayList<>();
105     List<String> ids = new ArrayList<>();
106     ids.add(identifier);
107
108     BufferedReader br = null;
109     try
110     {
111       URL url = getUrl(identifier);
112       if (url != null)
113       {
114         br = getHttpResponse(url, ids);
115         if (br != null)
116         {
117           result = parseResponse(br);
118         }
119       }
120     } catch (IOException e)
121     {
122       // ignore
123     } finally
124     {
125       if (br != null)
126       {
127         try
128         {
129           br.close();
130         } catch (IOException e)
131         {
132           // ignore
133         }
134       }
135     }
136
137     return result;
138   }
139
140   /**
141    * Parses "primary_id" and "dbname" values from the JSON response and
142    * constructs a DBRefEntry. Returns a list of the DBRefEntry created. Note we
143    * don't parse "synonyms" as they appear to be either redirected or obsolete
144    * in Uniprot.
145    * 
146    * @param br
147    * @return
148    * @throws IOException
149    */
150   protected List<DBRefEntry> parseResponse(BufferedReader br)
151           throws IOException
152   {
153     JSONParser jp = new JSONParser();
154     List<DBRefEntry> result = new ArrayList<>();
155     try
156     {
157       JSONArray responses = (JSONArray) jp.parse(br);
158       Iterator rvals = responses.iterator();
159       while (rvals.hasNext())
160       {
161         JSONObject val = (JSONObject) rvals.next();
162         String db = val.get("dbname").toString();
163         String id = val.get("primary_id").toString();
164         if (db != null && id != null
165                 && !GO_GENE_ONTOLOGY.equals(db))
166         {
167           db = DBRefUtils.getCanonicalName(db);
168           DBRefEntry dbref = new DBRefEntry(db, getXRefVersion(), id);
169           result.add(dbref);
170         }
171       }
172     } catch (ParseException e)
173     {
174       // ignore
175     }
176     return result;
177   }
178
179   private String xrefVersion = "ENSEMBL:0";
180
181   /**
182    * version string for Xrefs - for 2.10, hardwired for ENSEMBL:0
183    * 
184    * @return
185    */
186   public String getXRefVersion()
187   {
188     return xrefVersion;
189   }
190
191   /**
192    * Returns the URL for the REST endpoint to fetch all cross-references for an
193    * identifier. Note this may return protein cross-references for nucleotide.
194    * Filter the returned list as required.
195    * 
196    * @param identifier
197    * @return
198    */
199   protected URL getUrl(String identifier)
200   {
201     String url = getDomain() + "/xrefs/id/" + identifier
202             + CONTENT_TYPE_JSON + "&all_levels=1";
203     try
204     {
205       return new URL(url);
206     } catch (MalformedURLException e)
207     {
208       return null;
209     }
210   }
211
212 }