pattern match for up added....
[jalview.git] / forester / java / src / org / forester / ws / uniprot / UniProtWsTools.java
1 // $Id:
2 // forester -- software libraries and applications
3 // for genomics and evolutionary biology research.
4 //
5 // Copyright (C) 2010 Christian M Zmasek
6 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.ws.uniprot;
27
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.io.InputStreamReader;
31 import java.io.UnsupportedEncodingException;
32 import java.net.URL;
33 import java.net.URLConnection;
34 import java.net.URLEncoder;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
39
40 import org.forester.util.ForesterUtil;
41
42 public final class UniProtWsTools {
43
44     public enum Db {
45         UNKNOWN, UNIPROT;
46     }
47     public final static String   BASE_URL           = "http://www.uniprot.org/";
48     private final static String  URL_ENC            = "UTF-8";
49     // uniprot/expasy accession number format (6 chars):
50     // letter digit letter-or-digit letter-or-digit letter-or-digit digit
51     private final static Pattern UNIPROT_AC_PATTERN = Pattern
52                                                             .compile( "^.*[^a-zA-Z0-9]?([A-NR-ZOPQ]\\d[A-Z0-9]{3}\\d)[^a-zA-Z0-9]?" );
53     private final static boolean DEBUG              = false;
54
55     private static String encode( final String str ) throws UnsupportedEncodingException {
56         return URLEncoder.encode( str.trim(), URL_ENC );
57     }
58
59     /**
60      * Return null if no match.
61      * 
62      * @param query
63      * @param db 
64      * @return
65      */
66     static public String parseUniProtAccessor( final String query ) {
67         final Matcher m = UNIPROT_AC_PATTERN.matcher( query );
68         if ( m.lookingAt() ) {
69             return m.group( 1 );
70         }
71         else {
72             return null;
73         }
74     }
75
76     public static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String cn, final int max_taxonomies_return )
77             throws IOException {
78         final List<String> result = getTaxonomyStringFromCommonName( cn, max_taxonomies_return );
79         if ( result.size() > 0 ) {
80             return parseUniProtTaxonomy( result );
81         }
82         return null;
83     }
84
85     public static List<UniProtTaxonomy> getTaxonomiesFromCommonNameStrict( final String cn,
86                                                                            final int max_taxonomies_return )
87             throws IOException {
88         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromCommonName( cn, max_taxonomies_return );
89         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
90             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
91             for( final UniProtTaxonomy taxonomy : taxonomies ) {
92                 if ( taxonomy.getCommonName().equalsIgnoreCase( cn ) ) {
93                     filtered_taxonomies.add( taxonomy );
94                 }
95             }
96             return filtered_taxonomies;
97         }
98         return null;
99     }
100
101     public static List<UniProtTaxonomy> getTaxonomiesFromId( final String id, final int max_taxonomies_return )
102             throws IOException {
103         final List<String> result = getTaxonomyStringFromId( id, max_taxonomies_return );
104         if ( result.size() > 0 ) {
105             return parseUniProtTaxonomy( result );
106         }
107         return null;
108     }
109
110     public static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String sn,
111                                                                          final int max_taxonomies_return )
112             throws IOException {
113         // Hack!  Craniata? .. 
114         if ( sn.equals( "Drosophila" ) ) {
115             return hack( UniProtTaxonomy.DROSOPHILA_GENUS );
116         }
117         else if ( sn.equals( "Xenopus" ) ) {
118             return hack( UniProtTaxonomy.XENOPUS_GENUS );
119         }
120         final List<String> result = getTaxonomyStringFromScientificName( sn, max_taxonomies_return );
121         if ( result.size() > 0 ) {
122             return parseUniProtTaxonomy( result );
123         }
124         return null;
125     }
126
127     /**
128      * Does not return "sub-types".
129      * For example, for "Mus musculus" only returns "Mus musculus"
130      * and not "Mus musculus", "Mus musculus bactrianus", ...
131      * 
132      */
133     public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
134                                                                                final int max_taxonomies_return )
135             throws IOException {
136         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
137         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
138             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
139             for( final UniProtTaxonomy taxonomy : taxonomies ) {
140                 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
141                     filtered_taxonomies.add( taxonomy );
142                 }
143             }
144             return filtered_taxonomies;
145         }
146         return null;
147     }
148
149     public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
150                                                                        final int max_taxonomies_return )
151             throws IOException {
152         String my_code = new String( code );
153         // Hacks!
154         if ( my_code.equals( "FUGRU" ) ) {
155             my_code = "TAKRU";
156         }
157         else if ( my_code.equals( "CAP" ) ) {
158             return hack( UniProtTaxonomy.CAPITELLA_TELATA_SPECIES );
159         }
160         final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
161         if ( result.size() > 0 ) {
162             return parseUniProtTaxonomy( result );
163         }
164         return null;
165     }
166
167     private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
168             throws IOException {
169         return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
170     }
171
172     private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
173             throws IOException {
174         return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
175     }
176
177     private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
178             throws IOException {
179         return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
180     }
181
182     private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
183             throws IOException {
184         return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
185     }
186
187     private static List<UniProtTaxonomy> hack( final UniProtTaxonomy tax ) {
188         final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
189         l.add( tax );
190         return l;
191     }
192
193     private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
194         final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
195         for( final String line : result ) {
196             if ( ForesterUtil.isEmpty( line ) ) {
197                 // Ignore empty lines.
198             }
199             else if ( line.startsWith( "Taxon" ) ) {
200                 //TODO next the check format FIXME
201             }
202             else {
203                 if ( line.split( "\t" ).length > 4 ) {
204                     taxonomies.add( new UniProtTaxonomy( line ) );
205                 }
206             }
207         }
208         return taxonomies;
209     }
210
211     public static List<String> queryUniprot( final String query, int max_lines_to_return ) throws IOException {
212         if ( ForesterUtil.isEmpty( query ) ) {
213             throw new IllegalArgumentException( "illegal attempt to use empty query " );
214         }
215         if ( max_lines_to_return < 1 ) {
216             max_lines_to_return = 1;
217         }
218         final URL url = new URL( BASE_URL + query );
219         if ( DEBUG ) {
220             System.out.println( "url: " + url.toString() );
221         }
222         final URLConnection urlc = url.openConnection();
223         final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
224         String line;
225         final List<String> result = new ArrayList<String>();
226         while ( ( line = in.readLine() ) != null ) {
227             result.add( line );
228             if ( result.size() > max_lines_to_return ) {
229                 break;
230             }
231         }
232         in.close();
233         return result;
234     }
235
236     public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
237             throws IOException {
238         final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
239         return UniProtEntry.createInstanceFromPlainText( lines );
240     }
241 }