JAL-1739 Javadoc updated for Lambda expression parser functions
[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.datamodel.AlignmentI;
24
25 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.net.MalformedURLException;
28 import java.net.URL;
29 import java.util.Arrays;
30 import java.util.List;
31 import java.util.function.Function;
32
33 import org.json.simple.JSONObject;
34 import org.json.simple.parser.JSONParser;
35 import org.json.simple.parser.ParseException;
36
37 /**
38  * A client for the Ensembl lookup REST endpoint
39  * 
40  * @author gmcarstairs
41  */
42 public class EnsemblLookup extends EnsemblRestClient
43 {
44   private static final String SPECIES = "species";
45
46   private static final String PARENT = "Parent";
47
48   private static final String OBJECT_TYPE_TRANSLATION = "Translation";
49   private static final String OBJECT_TYPE_TRANSCRIPT = "Transcript";
50   private static final String ID = "id";
51   private static final String OBJECT_TYPE_GENE = "Gene";
52   private static final String OBJECT_TYPE = "object_type";
53
54   /**
55    * Default constructor (to use rest.ensembl.org)
56    */
57   public EnsemblLookup()
58   {
59     super();
60   }
61
62   /**
63    * Constructor given the target domain to fetch data from
64    * 
65    * @param
66    */
67   public EnsemblLookup(String d)
68   {
69     super(d);
70   }
71
72   @Override
73   public String getDbName()
74   {
75     return "ENSEMBL";
76   }
77
78   @Override
79   public AlignmentI getSequenceRecords(String queries) throws Exception
80   {
81     return null;
82   }
83
84   @Override
85   protected URL getUrl(List<String> ids) throws MalformedURLException
86   {
87     String identifier = ids.get(0);
88     return getUrl(identifier);
89   }
90
91   /**
92    * @param identifier
93    * @return
94    */
95   protected URL getUrl(String identifier)
96   {
97     String url = getDomain() + "/lookup/id/" + identifier
98             + CONTENT_TYPE_JSON;
99     try
100     {
101       return new URL(url);
102     } catch (MalformedURLException e)
103     {
104       return null;
105     }
106   }
107
108   @Override
109   protected boolean useGetRequest()
110   {
111     return true;
112   }
113
114   @Override
115   protected String getRequestMimeType(boolean multipleIds)
116   {
117     return "application/json";
118   }
119
120   @Override
121   protected String getResponseMimeType()
122   {
123     return "application/json";
124   }
125
126   /**
127    * Calls the Ensembl lookup REST endpoint and returns
128    * <ul>
129    * <li>the 'id' for the identifier if its type is "Gene"</li>
130    * <li>the 'Parent' if its type is 'Transcript'</li>
131    * <ul>
132    * If the type is 'Translation', does a recursive call to this method, passing
133    * in the 'Parent' (transcript id).
134    * 
135    * @param identifier
136    * @return
137    */
138   public String getGeneId(String identifier)
139   {
140     return getResult(identifier, br -> parseGeneId(br));
141   }
142
143   /**
144    * Calls the Ensembl lookup REST endpoint and retrieves the 'species' for the
145    * given identifier, or null if not found
146    * 
147    * @param identifier
148    * @return
149    */
150   public String getSpecies(String identifier)
151   {
152     return getResult(identifier, br -> getAttribute(br, SPECIES));
153   }
154
155   /**
156    * Calls the /lookup/id rest service and delegates parsing of the JSON
157    * response to the supplied parser
158    * 
159    * @param identifier
160    * @param parser
161    * @return
162    */
163   protected String getResult(String identifier,
164           Function<BufferedReader, String> parser)
165   {
166     List<String> ids = Arrays.asList(new String[] { identifier });
167
168     BufferedReader br = null;
169     try
170     {
171       URL url = getUrl(identifier);
172       if (url != null)
173       {
174         br = getHttpResponse(url, ids);
175       }
176       return br == null ? null : parser.apply(br);
177     } catch (IOException e)
178     {
179       // ignore
180       return null;
181     } finally
182     {
183       if (br != null)
184       {
185         try
186         {
187           br.close();
188         } catch (IOException e)
189         {
190           // ignore
191         }
192       }
193     }
194   }
195
196   /**
197    * Answers the value of 'attribute' from the JSON response, or null if not
198    * found
199    * 
200    * @param br
201    * @param attribute
202    * @return
203    */
204   protected String getAttribute(BufferedReader br, String attribute)
205   {
206     String value = null;
207     JSONParser jp = new JSONParser();
208     try
209     {
210       JSONObject val = (JSONObject) jp.parse(br);
211       value = val.get(attribute).toString();
212     } catch (ParseException | NullPointerException | IOException e)
213     {
214       // ignore
215     }
216     return value;
217   }
218
219   /**
220    * Parses the JSON response and returns the gene identifier, or null if not
221    * found. If the returned object_type is Gene, returns the id, if Transcript
222    * returns the Parent. If it is Translation (peptide identifier), then the
223    * Parent is the transcript identifier, so we redo the search with this value.
224    * 
225    * @param br
226    * @return
227    */
228   protected String parseGeneId(BufferedReader br)
229   {
230     String geneId = null;
231     JSONParser jp = new JSONParser();
232     try
233     {
234       JSONObject val = (JSONObject) jp.parse(br);
235       String type = val.get(OBJECT_TYPE).toString();
236       if (OBJECT_TYPE_GENE.equalsIgnoreCase(type))
237       {
238         geneId = val.get(ID).toString();
239       }
240       else if (OBJECT_TYPE_TRANSCRIPT.equalsIgnoreCase(type))
241       {
242         geneId = val.get(PARENT).toString();
243       }
244       else if (OBJECT_TYPE_TRANSLATION.equalsIgnoreCase(type))
245       {
246         String transcriptId = val.get(PARENT).toString();
247         try
248         {
249           geneId = getGeneId(transcriptId);
250         } catch (StackOverflowError e)
251         {
252           /*
253            * unlikely data condition error!
254            */
255           System.err
256                   .println("** Ensembl lookup "
257                           + getUrl(transcriptId).toString()
258                           + " looping on Parent!");
259         }
260       }
261     } catch (ParseException | IOException e)
262     {
263       // ignore
264     }
265     return geneId;
266   }
267
268 }