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