JAL-3193 removal of rest.ensemblgenomes.org
[jalview.git] / src / jalview / ext / ensembl / EnsemblFeatures.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.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.Sequence;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.io.gff.SequenceOntologyI;
29 import jalview.util.JSONUtils;
30
31 import java.io.BufferedReader;
32 import java.io.IOException;
33 import java.net.MalformedURLException;
34 import java.net.URL;
35 import java.util.ArrayList;
36 import java.util.Iterator;
37 import java.util.List;
38
39 import org.json.simple.JSONArray;
40 import org.json.simple.JSONObject;
41 import org.json.simple.parser.JSONParser;
42 import org.json.simple.parser.ParseException;
43
44 /**
45  * A client for fetching and processing Ensembl feature data in GFF format by
46  * calling the overlap REST service
47  * 
48  * @author gmcarstairs
49  * @see http://rest.ensembl.org/documentation/info/overlap_id
50  */
51 class EnsemblFeatures extends EnsemblRestClient
52 {
53   /*
54    * The default features to retrieve from Ensembl
55    * can override in getSequenceRecords parameter
56    */
57   private EnsemblFeatureType[] featuresWanted = { EnsemblFeatureType.cds,
58       EnsemblFeatureType.exon, EnsemblFeatureType.variation };
59
60   /**
61    * Default constructor (to use rest.ensembl.org)
62    */
63   public EnsemblFeatures()
64   {
65     super();
66   }
67
68   @Override
69   public String getDbName()
70   {
71     return "ENSEMBL (features)";
72   }
73
74   /**
75    * Makes a query to the REST overlap endpoint for the given sequence
76    * identifier. This returns an 'alignment' consisting of one 'dummy sequence'
77    * (the genomic sequence for which overlap features are returned by the
78    * service). This sequence will have on it sequence features which are the
79    * real information of interest, such as CDS regions or sequence variations.
80    */
81   @Override
82   public AlignmentI getSequenceRecords(String query) throws IOException
83   {
84     // TODO: use a vararg String... for getSequenceRecords instead?
85     List<String> queries = new ArrayList<>();
86     queries.add(query);
87     BufferedReader fp = getSequenceReader(queries);
88     if (fp == null)
89     {
90       return null;
91     }
92
93     SequenceI seq = parseFeaturesJson(fp);
94     return new Alignment(new SequenceI[] { seq });
95   }
96
97   /**
98    * Parses the JSON response into Jalview sequence features and attaches them
99    * to a dummy sequence
100    * 
101    * @param br
102    * @return
103    */
104   private SequenceI parseFeaturesJson(BufferedReader br)
105   {
106     SequenceI seq = new Sequence("Dummy", "");
107
108     JSONParser jp = new JSONParser();
109     try
110     {
111       JSONArray responses = (JSONArray) jp.parse(br);
112       Iterator rvals = responses.iterator();
113       while (rvals.hasNext())
114       {
115         try
116         {
117           JSONObject obj = (JSONObject) rvals.next();
118           String type = obj.get("feature_type").toString();
119           int start = Integer.parseInt(obj.get("start").toString());
120           int end = Integer.parseInt(obj.get("end").toString());
121           String source = obj.get("source").toString();
122           String strand = obj.get("strand").toString();
123           String alleles = JSONUtils
124                   .arrayToList((JSONArray) obj.get("alleles"));
125           String clinSig = JSONUtils
126                   .arrayToList(
127                           (JSONArray) obj.get("clinical_significance"));
128
129           /*
130            * convert 'variation' to 'sequence_variant', and 'cds' to 'CDS'
131            * so as to have a valid SO term for the feature type
132            * ('gene', 'exon', 'transcript' don't need any conversion)
133            */
134           if ("variation".equals(type))
135           {
136             type = SequenceOntologyI.SEQUENCE_VARIANT;
137           }
138           else if (SequenceOntologyI.CDS.equalsIgnoreCase((type)))
139           {
140             type = SequenceOntologyI.CDS;
141           }
142           
143           String desc = getFirstNotNull(obj, "alleles", "external_name",
144                   JSON_ID);
145           SequenceFeature sf = new SequenceFeature(type, desc, start, end,
146                   source);
147           sf.setStrand("1".equals(strand) ? "+" : "-");
148           setFeatureAttribute(sf, obj, "id");
149           setFeatureAttribute(sf, obj, "Parent");
150           setFeatureAttribute(sf, obj, "consequence_type");
151           sf.setValue("alleles", alleles);
152           sf.setValue("clinical_significance", clinSig);
153
154           seq.addSequenceFeature(sf);
155         } catch (Throwable t)
156         {
157           // ignore - keep trying other features
158         }
159       }
160     } catch (ParseException | IOException e)
161     {
162       // ignore
163     }
164
165     return seq;
166   }
167
168   /**
169    * Returns the first non-null attribute found (if any) as a string, formatted
170    * suitably for display as feature description or tooltip. Answers null if
171    * none of the attribute keys is present.
172    * 
173    * @param obj
174    * @param keys
175    * @return
176    */
177   protected String getFirstNotNull(JSONObject obj, String... keys)
178   {
179     String desc = null;
180
181     for (String key : keys)
182     {
183       Object val = obj.get(key);
184       if (val != null)
185       {
186         String s = val instanceof JSONArray
187                 ? JSONUtils.arrayToList((JSONArray) val)
188                 : val.toString();
189         if (!s.isEmpty())
190         {
191           return s;
192         }
193       }
194     }
195     return desc;
196   }
197
198   /**
199    * A helper method that reads the 'key' entry in the JSON object, and if not
200    * null, sets its string value as an attribute on the sequence feature
201    * 
202    * @param sf
203    * @param obj
204    * @param key
205    */
206   protected void setFeatureAttribute(SequenceFeature sf, JSONObject obj,
207           String key)
208   {
209     Object object = obj.get(key);
210     if (object != null)
211     {
212       sf.setValue(key, object.toString());
213     }
214   }
215
216   /**
217    * Returns a URL for the REST overlap endpoint
218    * 
219    * @param ids
220    * @return
221    */
222   @Override
223   protected URL getUrl(List<String> ids) throws MalformedURLException
224   {
225     StringBuffer urlstring = new StringBuffer(128);
226     urlstring.append(getDomain()).append("/overlap/id/").append(ids.get(0));
227
228     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
229     urlstring.append("?content-type=" + getResponseMimeType());
230
231     /*
232      * specify object_type=gene in case is shared by transcript and/or protein;
233      * currently only fetching features for gene sequences;
234      * refactor in future if needed to fetch for transcripts
235      */
236     urlstring.append("&").append(OBJECT_TYPE).append("=")
237             .append(OBJECT_TYPE_GENE);
238
239     /*
240      * specify  features to retrieve
241      * @see http://rest.ensembl.org/documentation/info/overlap_id
242      * could make the list a configurable entry in .jalview_properties
243      */
244     for (EnsemblFeatureType feature : featuresWanted)
245     {
246       urlstring.append("&feature=").append(feature.name());
247     }
248
249     return new URL(urlstring.toString());
250   }
251
252   @Override
253   protected boolean useGetRequest()
254   {
255     return true;
256   }
257
258   /**
259    * Returns the MIME type for GFF3. For GET requests the Content-type header
260    * describes the required encoding of the response.
261    */
262   @Override
263   protected String getRequestMimeType()
264   {
265     return "application/json";
266   }
267
268   /**
269    * Returns the MIME type wanted for the response
270    */
271   @Override
272   protected String getResponseMimeType()
273   {
274     return "application/json";
275   }
276
277   /**
278    * Overloaded method that allows a list of features to retrieve to be
279    * specified
280    * 
281    * @param accId
282    * @param features
283    * @return
284    * @throws IOException
285    */
286   protected AlignmentI getSequenceRecords(String accId,
287           EnsemblFeatureType[] features) throws IOException
288   {
289     featuresWanted = features;
290     return getSequenceRecords(accId);
291   }
292 }