JAL-3193 removal of rest.ensemblgenomes.org
[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   @Override
60   public String getDbName()
61   {
62     return "ENSEMBL";
63   }
64
65   @Override
66   public AlignmentI getSequenceRecords(String queries) throws Exception
67   {
68     return null;
69   }
70
71   @Override
72   protected URL getUrl(List<String> ids) throws MalformedURLException
73   {
74     String identifier = ids.get(0);
75     return getUrl(identifier, null);
76   }
77
78   /**
79    * Gets the url for lookup of the given identifier, optionally with objectType
80    * also specified in the request
81    * 
82    * @param identifier
83    * @param objectType
84    * @return
85    */
86   protected URL getUrl(String identifier, String objectType)
87   {
88     String url = getDomain() + "/lookup/id/" + identifier
89             + CONTENT_TYPE_JSON;
90     if (objectType != null)
91     {
92       url += "&" + OBJECT_TYPE + "=" + objectType;
93     }
94
95     try
96     {
97       return new URL(url);
98     } catch (MalformedURLException e)
99     {
100       return null;
101     }
102   }
103
104   @Override
105   protected boolean useGetRequest()
106   {
107     return true;
108   }
109
110   /**
111    * Returns the gene id related to the given identifier (which may be for a
112    * gene, transcript or protein), or null if none is found
113    * 
114    * @param identifier
115    * @return
116    */
117   public String getGeneId(String identifier)
118   {
119     return getGeneId(identifier, null);
120   }
121
122   /**
123    * Returns the gene id related to the given identifier (which may be for a
124    * gene, transcript or protein), or null if none is found
125    * 
126    * @param identifier
127    * @param objectType
128    * @return
129    */
130   public String getGeneId(String identifier, String objectType)
131   {
132     return parseGeneId(getResult(identifier, objectType));
133   }
134
135   /**
136    * Parses the JSON response and returns the gene identifier, or null if not
137    * found. If the returned object_type is Gene, returns the id, if Transcript
138    * returns the Parent. If it is Translation (peptide identifier), then the
139    * Parent is the transcript identifier, so we redo the search with this value.
140    * 
141    * @param br
142    * @return
143    */
144   protected String parseGeneId(JSONObject val)
145   {
146     if (val == null)
147     {
148       return null;
149     }
150     String geneId = null;
151     String type = val.get(OBJECT_TYPE).toString();
152     if (OBJECT_TYPE_GENE.equalsIgnoreCase(type))
153     {
154       // got the gene - just returns its id
155       geneId = val.get(JSON_ID).toString();
156     }
157     else if (OBJECT_TYPE_TRANSCRIPT.equalsIgnoreCase(type))
158     {
159       // got the transcript - return its (Gene) Parent
160       geneId = val.get(PARENT).toString();
161     }
162     else if (OBJECT_TYPE_TRANSLATION.equalsIgnoreCase(type))
163     {
164       // got the protein - get its Parent, restricted to type Transcript
165       String transcriptId = val.get(PARENT).toString();
166       geneId = getGeneId(transcriptId, OBJECT_TYPE_TRANSCRIPT);
167     }
168
169     return geneId;
170   }
171
172   /**
173    * Calls the Ensembl lookup REST endpoint and retrieves the 'species' for the
174    * given identifier, or null if not found
175    * 
176    * @param identifier
177    * @return
178    */
179   public String getSpecies(String identifier)
180   {
181     String species = null;
182     JSONObject json = getResult(identifier, null);
183     if (json != null)
184     {
185       Object o = json.get(SPECIES);
186       if (o != null)
187       {
188         species = o.toString();
189       }
190     }
191     return species;
192   }
193
194   /**
195    * Calls the /lookup/id rest service and returns the response as a JSONObject,
196    * or null if any error
197    * 
198    * @param identifier
199    * @param objectType
200    *          (optional)
201    * @return
202    */
203   protected JSONObject getResult(String identifier, String objectType)
204   {
205     List<String> ids = Arrays.asList(new String[] { identifier });
206
207     BufferedReader br = null;
208     try
209     {
210       URL url = getUrl(identifier, objectType);
211
212       if (url != null)
213       {
214         br = getHttpResponse(url, ids);
215       }
216       return br == null ? null : (JSONObject) (new JSONParser().parse(br));
217     } catch (IOException | ParseException e)
218     {
219       System.err.println("Error parsing " + identifier + " lookup response "
220               + e.getMessage());
221       return null;
222     } finally
223     {
224       if (br != null)
225       {
226         try
227         {
228           br.close();
229         } catch (IOException e)
230         {
231           // ignore
232         }
233       }
234     }
235   }
236
237   /**
238    * Calls the /lookup/id rest service for the given id, and if successful,
239    * parses and returns the gene's chromosomal coordinates
240    * 
241    * @param geneId
242    * @return
243    */
244   public GeneLociI getGeneLoci(String geneId)
245   {
246     return parseGeneLoci(getResult(geneId, OBJECT_TYPE_GENE));
247   }
248
249   /**
250    * Parses the /lookup/id response for species, asssembly_name,
251    * seq_region_name, start, end and returns an object that wraps them, or null
252    * if unsuccessful
253    * 
254    * @param json
255    * @return
256    */
257   GeneLociI parseGeneLoci(JSONObject json)
258   {
259     if (json == null)
260     {
261       return null;
262     }
263
264     try
265     {
266       final String species = json.get("species").toString();
267       final String assembly = json.get("assembly_name").toString();
268       final String chromosome = json.get("seq_region_name").toString();
269       String strand = json.get("strand").toString();
270       int start = Integer.parseInt(json.get("start").toString());
271       int end = Integer.parseInt(json.get("end").toString());
272       int fromEnd = end - start + 1;
273       boolean reverseStrand = "-1".equals(strand);
274       int toStart = reverseStrand ? end : start;
275       int toEnd = reverseStrand ? start : end;
276       List<int[]> fromRange = Collections.singletonList(new int[] { 1,
277           fromEnd });
278       List<int[]> toRange = Collections.singletonList(new int[] { toStart,
279           toEnd });
280       final MapList map = new MapList(fromRange, toRange, 1, 1);
281       return new GeneLociI()
282       {
283
284         @Override
285         public String getSpeciesId()
286         {
287           return species == null ? "" : species;
288         }
289
290         @Override
291         public String getAssemblyId()
292         {
293           return assembly;
294         }
295
296         @Override
297         public String getChromosomeId()
298         {
299           return chromosome;
300         }
301
302         @Override
303         public MapList getMap()
304         {
305           return map;
306         }
307       };
308     } catch (NullPointerException | NumberFormatException e)
309     {
310       Cache.log.error("Error looking up gene loci: " + e.getMessage());
311       e.printStackTrace();
312     }
313     return null;
314   }
315
316 }