102dffbddb8b3140cb06c26dd1aa9362fadb7540
[jalview.git] / src / jalview / ext / ensembl / EnsemblLookup.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.bin.Cache;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.GeneLociI;
26 import jalview.util.MapList;
27
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.net.MalformedURLException;
31 import java.net.URL;
32 import java.util.Arrays;
33 import java.util.Collections;
34 import java.util.List;
35
36 import org.json.simple.JSONObject;
37 import org.json.simple.parser.JSONParser;
38 import org.json.simple.parser.ParseException;
39
40 /**
41  * A client for the Ensembl /lookup REST endpoint, used to find the gene
42  * identifier given a gene, transcript or protein identifier, or to extract the
43  * species or chromosomal coordinates from the same service response
44  * 
45  * @author gmcarstairs
46  */
47 public class EnsemblLookup extends EnsemblRestClient
48 {
49   private static final String SPECIES = "species";
50
51   /**
52    * Default constructor (to use rest.ensembl.org)
53    */
54   public EnsemblLookup()
55   {
56     super();
57   }
58
59   /**
60    * Constructor given the target domain to fetch data from
61    * 
62    * @param
63    */
64   public EnsemblLookup(String d)
65   {
66     super(d);
67   }
68
69   @Override
70   public String getDbName()
71   {
72     return "ENSEMBL";
73   }
74
75   @Override
76   public AlignmentI getSequenceRecords(String queries) throws Exception
77   {
78     return null;
79   }
80
81   @Override
82   protected URL getUrl(List<String> ids) throws MalformedURLException
83   {
84     String identifier = ids.get(0);
85     return getUrl(identifier, null);
86   }
87
88   /**
89    * Gets the url for lookup of the given identifier, optionally with objectType
90    * also specified in the request
91    * 
92    * @param identifier
93    * @param objectType
94    * @return
95    */
96   protected URL getUrl(String identifier, String objectType)
97   {
98     String url = getDomain() + "/lookup/id/" + identifier
99             + CONTENT_TYPE_JSON;
100     if (objectType != null)
101     {
102       url += "&" + OBJECT_TYPE + "=" + objectType;
103     }
104
105     try
106     {
107       return new URL(url);
108     } catch (MalformedURLException e)
109     {
110       return null;
111     }
112   }
113
114   @Override
115   protected boolean useGetRequest()
116   {
117     return true;
118   }
119
120   @Override
121   protected String getRequestMimeType(boolean multipleIds)
122   {
123     return "application/json";
124   }
125
126   @Override
127   protected String getResponseMimeType()
128   {
129     return "application/json";
130   }
131
132   /**
133    * Returns the gene id related to the given identifier (which may be for a
134    * gene, transcript or protein)
135    * 
136    * @param identifier
137    * @return
138    */
139   public String getGeneId(String identifier)
140   {
141     return getGeneId(identifier, null);
142   }
143
144   /**
145    * Returns the gene id related to the given identifier (which may be for a
146    * gene, transcript or protein)
147    * 
148    * @param identifier
149    * @param objectType
150    * @return
151    */
152   public String getGeneId(String identifier, String objectType)
153   {
154     List<String> ids = Arrays.asList(new String[] { identifier });
155
156     BufferedReader br = null;
157     try
158     {
159       URL url = getUrl(identifier, objectType);
160       if (url != null)
161       {
162         br = getHttpResponse(url, ids);
163       }
164       return br == null ? null : parseResponse(br);
165     } catch (IOException e)
166     {
167       // ignore
168       return null;
169     } finally
170     {
171       if (br != null)
172       {
173         try
174         {
175           br.close();
176         } catch (IOException e)
177         {
178           // ignore
179         }
180       }
181     }
182   }
183
184   /**
185    * Parses the JSON response and returns the gene identifier, or null if not
186    * found. If the returned object_type is Gene, returns the id, if Transcript
187    * returns the Parent. If it is Translation (peptide identifier), then the
188    * Parent is the transcript identifier, so we redo the search with this value.
189    * 
190    * @param br
191    * @return
192    * @throws IOException
193    */
194   protected String parseResponse(BufferedReader br) throws IOException
195   {
196     String geneId = null;
197     JSONParser jp = new JSONParser();
198     try
199     {
200       JSONObject val = (JSONObject) jp.parse(br);
201       String type = val.get(OBJECT_TYPE).toString();
202       if (OBJECT_TYPE_GENE.equalsIgnoreCase(type))
203       {
204         // got the gene - just returns its id
205         geneId = val.get(JSON_ID).toString();
206       }
207       else if (OBJECT_TYPE_TRANSCRIPT.equalsIgnoreCase(type))
208       {
209         // got the transcript - return its (Gene) Parent
210         geneId = val.get(PARENT).toString();
211       }
212       else if (OBJECT_TYPE_TRANSLATION.equalsIgnoreCase(type))
213       {
214         // got the protein - get its Parent, restricted to type Transcript
215         String transcriptId = val.get(PARENT).toString();
216         geneId = getGeneId(transcriptId, OBJECT_TYPE_TRANSCRIPT);
217       }
218     } catch (ParseException e)
219     {
220       // ignore
221     }
222     return geneId;
223   }
224
225   /**
226    * Calls the Ensembl lookup REST endpoint and retrieves the 'species' for the
227    * given identifier, or null if not found
228    * 
229    * @param identifier
230    * @return
231    */
232   public String getSpecies(String identifier)
233   {
234     String species = null;
235     JSONObject json = getResult(identifier, null);
236     if (json != null)
237     {
238       Object o = json.get(SPECIES);
239       if (o != null)
240       {
241         species = o.toString();
242       }
243     }
244     return species;
245   }
246
247   /**
248    * Calls the /lookup/id rest service and returns the response as a JSONObject,
249    * or null if any error
250    * 
251    * @param identifier
252    * @param objectType
253    *          (optional)
254    * @return
255    */
256   protected JSONObject getResult(String identifier, String objectType)
257   {
258     List<String> ids = Arrays.asList(new String[] { identifier });
259
260     BufferedReader br = null;
261     try
262     {
263       URL url = getUrl(identifier, objectType);
264
265       if (url != null)
266       {
267         br = getHttpResponse(url, ids);
268       }
269       return br == null ? null : (JSONObject) (new JSONParser().parse(br));
270     } catch (IOException | ParseException e)
271     {
272       System.err.println("Error parsing " + identifier + " lookup response "
273               + e.getMessage());
274       return null;
275     } finally
276     {
277       if (br != null)
278       {
279         try
280         {
281           br.close();
282         } catch (IOException e)
283         {
284           // ignore
285         }
286       }
287     }
288   }
289
290   /**
291    * Calls the /lookup/id rest service for the given id, and if successful,
292    * parses and returns the gene's chromosomal coordinates
293    * 
294    * @param geneId
295    * @return
296    */
297   public GeneLociI getGeneLoci(String geneId)
298   {
299     return parseGeneLoci(getResult(geneId, OBJECT_TYPE_GENE));
300   }
301
302   /**
303    * Parses the /lookup/id response for species, asssembly_name,
304    * seq_region_name, start, end and returns an object that wraps them, or null
305    * if unsuccessful
306    * 
307    * @param json
308    * @return
309    */
310   GeneLociI parseGeneLoci(JSONObject json)
311   {
312     if (json == null)
313     {
314       return null;
315     }
316
317     try
318     {
319       final String species = json.get("species").toString();
320       final String assembly = json.get("assembly_name").toString();
321       final String chromosome = json.get("seq_region_name").toString();
322       String strand = json.get("strand").toString();
323       int start = Integer.parseInt(json.get("start").toString());
324       int end = Integer.parseInt(json.get("end").toString());
325       int fromEnd = end - start + 1;
326       boolean reverseStrand = "-1".equals(strand);
327       int toStart = reverseStrand ? end : start;
328       int toEnd = reverseStrand ? start : end;
329       List<int[]> fromRange = Collections.singletonList(new int[] { 1,
330           fromEnd });
331       List<int[]> toRange = Collections.singletonList(new int[] { toStart,
332           toEnd });
333       final MapList map = new MapList(fromRange, toRange, 1, 1);
334       return new GeneLociI()
335       {
336
337         @Override
338         public String getSpeciesId()
339         {
340           return species == null ? "" : species;
341         }
342
343         @Override
344         public String getAssemblyId()
345         {
346           return assembly;
347         }
348
349         @Override
350         public String getChromosomeId()
351         {
352           return chromosome;
353         }
354
355         @Override
356         public MapList getMap()
357         {
358           return map;
359         }
360       };
361     } catch (NullPointerException | NumberFormatException e)
362     {
363       Cache.log.error("Error looking up gene loci: " + e.getMessage());
364       e.printStackTrace();
365     }
366     return null;
367   }
368
369 }