75598a067e41c35150b7f4a39b11fc30ff9cb756
[jalview.git] / src / jalview / ext / ensembl / EnsemblSymbol.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 java.io.BufferedReader;
24 import java.io.IOException;
25 import java.net.MalformedURLException;
26 import java.net.URL;
27 import java.util.ArrayList;
28 import java.util.Iterator;
29 import java.util.List;
30
31 import org.json.simple.JSONArray;
32 import org.json.simple.JSONObject;
33 import org.json.simple.parser.JSONParser;
34 import org.json.simple.parser.ParseException;
35
36 /**
37  * A client for the Ensembl xrefs/symbol REST service;
38  * 
39  * @see http://rest.ensembl.org/documentation/info/xref_external
40  * @author gmcarstairs
41  *
42  */
43 public class EnsemblSymbol extends EnsemblXref
44 {
45   private static final String GENE = "gene";
46   private static final String TYPE = "type";
47   private static final String ID = "id";
48
49   /**
50    * Constructor given the target domain to fetch data from
51    * 
52    * @param domain
53    * @param dbName
54    * @param dbVersion
55    */
56   public EnsemblSymbol(String domain, String dbName, String dbVersion)
57   {
58     super(domain, dbName, dbVersion);
59   }
60
61   /**
62    * Returns the first "id" value in gene identifier format from the JSON
63    * response, or null if none found
64    * 
65    * @param br
66    * @return
67    * @throws IOException
68    */
69   protected String parseSymbolResponse(BufferedReader br) throws IOException
70   {
71     JSONParser jp = new JSONParser();
72     String result = null;
73     try
74     {
75       JSONArray responses = (JSONArray) jp.parse(br);
76       Iterator rvals = responses.iterator();
77       while (rvals.hasNext())
78       {
79         JSONObject val = (JSONObject) rvals.next();
80         String id = val.get(ID).toString();
81         String type = val.get(TYPE).toString();
82         if (id != null && GENE.equals(type))
83         {
84           result = id;
85           break;
86         }
87       }
88     } catch (ParseException e)
89     {
90       // ignore
91     }
92     return result;
93   }
94
95   /**
96    * Constructs the URL for the REST symbol endpoint
97    * 
98    * @param id
99    *          the accession id (Ensembl or external)
100    * @param species
101    *          a species name recognisable by Ensembl
102    * @param type
103    *          an optional type to filter the response (gene, transcript,
104    *          translation)
105    * @return
106    */
107   protected URL getUrl(String id, Species species, String... type)
108   {
109     StringBuilder sb = new StringBuilder();
110     sb.append(getDomain()).append("/xrefs/symbol/")
111             .append(species.toString()).append("/").append(id)
112             .append(CONTENT_TYPE_JSON);
113     for (String t : type)
114     {
115       sb.append("&object_type=").append(t);
116     }
117     try
118     {
119       String url = sb.toString();
120       return new URL(url);
121     } catch (MalformedURLException e)
122     {
123       return null;
124     }
125   }
126
127   /**
128    * Calls the Ensembl xrefs REST 'symbol' endpoint and retrieves any gene ids
129    * for the given identifier, for any known model organisms
130    * 
131    * @param identifier
132    * @return
133    */
134   public List<String> getGeneIds(String identifier)
135   {
136     List<String> result = new ArrayList<String>();
137     List<String> ids = new ArrayList<String>();
138     ids.add(identifier);
139
140     String[] queries = identifier.split(getAccessionSeparator());
141     BufferedReader br = null;
142     try
143     {
144       for (String query : queries)
145       {
146         for (Species taxon : Species.getModelOrganisms())
147         {
148           URL url = getUrl(query, taxon, GENE);
149           if (url != null)
150           {
151             br = getHttpResponse(url, ids);
152             if (br != null)
153             {
154               String geneId = parseSymbolResponse(br);
155               System.out.println(url + " returned " + geneId);
156               if (geneId != null && !result.contains(geneId))
157               {
158                 result.add(geneId);
159               }
160             }
161           }
162         }
163       }
164     } catch (IOException e)
165     {
166       // ignore
167     } finally
168     {
169       if (br != null)
170       {
171         try
172         {
173           br.close();
174         } catch (IOException e)
175         {
176           // ignore
177         }
178       }
179     }
180     return result;
181   }
182
183 }